react-native
  1. react-native-picker

React-Native Picker

Syntax

The component in React-Native can be used to implement a dropdown selection menu.

import React, { useState } from 'react';
import { View, Picker } from 'react-native';

function SelectColor() {
  const [selectedColor, setSelectedColor] = useState('blue');

  return (
    <View>
      <Picker
        selectedValue={selectedColor}
        onValueChange={(itemValue, itemIndex) => setSelectedColor(itemValue)}
      >
        <Picker.Item label="Blue" value="blue" />
        <Picker.Item label="Green" value="green" />
        <Picker.Item label="Red" value="red" />
      </Picker>
    </View>
  );
}

export default SelectColor;

Example

import React, { useState } from 'react';
import { View, Text, Picker } from 'react-native';

function SelectColor() {
  const [selectedColor, setSelectedColor] = useState('blue');

  return (
    <View>
      <Text style={{ fontSize: 20, fontWeight: 'bold' }}>Select a color:</Text>
      <Picker
        selectedValue={selectedColor}
        style={{ height: 50, width: 150 }}
        onValueChange={(itemValue, itemIndex) => setSelectedColor(itemValue)}
      >
        <Picker.Item label="Blue" value="blue" />
        <Picker.Item label="Green" value="green" />
        <Picker.Item label="Red" value="red" />
      </Picker>
      <Text style={{ fontSize: 20 }}>You selected: {selectedColor}</Text>
    </View>
  );
}

export default SelectColor;

Output

The selected color will be displayed in the app as soon as the user selects an option from the dropdown.

Explanation

The component in React-Native can be used to implement a dropdown selection menu.

The selectedValue prop specifies the value that should be selected by default, while the onValueChange prop specifies the change event handler.

Inside the component, we define each option using the <Picker.Item> component.

Use

can be used to implement any dropdown selection menu in a React-Native app.

Important Points

  • selectedValue prop must be set to match one of the value props of the <Picker.Item> components.
  • The onValueChange prop is triggered whenever a new value is selected from the dropdown.
  • The component is only available on iOS and Android platforms.

Summary

The component in React-Native is a versatile tool that can be used to implement dropdown selection menus in a mobile app. By using the selectedValue and onValueChange props, we can provide a simple and intuitive user experience.

Published on: