How to create one picker component in React Native

Introduction :

Picker provides a dropdown list of items to pick from. On Android, it can be a dialog or dropdown. In this post, I will quickly show you how to use Picker in react native with one example.

Props for Picker :

Following props are available for Picker component :

[Android] enabled :

Marking it false will disable it on Android i.e. it will not respond on click.

[iOS] itemStyle :

Text style to add to each of the items.

[Android] mode :

Defines how to display the items on click. It can be any one of dialog and dropdown. dialog shows one modal dialog with all these items and dropdown shows one dropdown of these items.

onValueChange :

It takes a function that is called once the value is changed or a different value is clicked. The function receives the value of the item and the position of the item.

[Android] prompt :

Title string for modal view on Android.

selectedValue :

Value of the selected item.

style :

Style to add.

testID :

ID to find this view in test cases.

Example Program :

Let’s take a look at the program below :

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

const App = () => {
  const [day, setDay] = useState('Sun');
  const [month, setMonth] = useState('January');

  const days = ['Sun', 'Mon', 'Tues', 'Thurs', 'Fri', 'Sat'];
  const months = [
    'Jan',
    'Feb',
    'March',
    'April',
    'May',
    'June',
    'July',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];

  return (
    <View style={styles.parentView}>
      <Picker
        selectedValue={day}
        style={{height: 60, width: 150, borderColor: 'black'}}
        onValueChange={itemValue => setDay(itemValue)}>
        {days.map((item, index) => (
          <Picker.Item label={item} value={index} key={index} />
        ))}
      </Picker>

      <Picker
        selectedValue={month}
        style={{height: 60, width: 150, borderColor: 'black'}}
        onValueChange={itemValue => setMonth(itemValue)}
        mode="dropdown">
        {months.map((item, index) => (
          <Picker.Item label={item} value={index} key={index} />
        ))}
      </Picker>
    </View>
  );
};

const styles = StyleSheet.create({
  parentView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 22,
  },
});

export default App;

Here, we are using two pickers. One is a dropdown picker and another one is popup.

It will give the following output :

React Native picker

It will look different on iOS.