Creating a Picker for Android/iOS using React Native

Tiempo de lectura: 2 minutos

Reading Time: 2 minutes

I’m going to show you how to create a picker component in Android/iOS using React Native.

The first thing we need to do is import the react-native-picker-select library.

To import this library, we need to execute these two commands (one for the library and one for the dependency):

npm install react-native-picker-select

expo install @react-native-picker/picker

Once installed, we can create the component. Let’s create a new component and add the following:

import SelectInputPicker from 'react-native-picker-select';

Now let’s create the render:

const [valueInput, setValueInput] = useState("");

var arrayLista= [
    { label: "Cars", value: 'cars' },
    { label: "Boats", value: 'boats' }
];

return (
     setValueInput(value)}
        items={arrayLista}
    />
);

We have created all the necessary variables to create our picker:

  1. First, we create a State to store/update the selected value in the picker.
  2. arrayLista is the list of values that we want to appear in the picker (it’s a JSON).
  3. We create the imported component:
    • onValueChange – Gets the value selected by the user.
    • items – Assigns the values created in arrayLista (JSON).

With this, we have our component working on iOS/Android.

If we want to set a default value, we need to add a placeholder as follows:

placeholder={{ label: "Select a transportation", value: 0 }}

We need to add label and value for the placeholder to be displayed and work correctly.

It will look like this:

const [valueInput, setValueInput] = useState("");

var arrayLista= [
    { label: "Cars", value: 'cars' },
    { label: "Boats", value: 'boats' }
];

return (
     setValueInput(value)}
        items={arrayLista}
        placeholder={{ label: "Select a transportation", value: 0 }}
    />
);

Leave a Comment