Create a Select (Picker) Component in React Native

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

In today’s React tutorial, I will show you how to create a select (combo or picker) where you can choose different options.

The first thing we need to do is import the library we are going to use (react-native-picker-select):

npm install react-native-picker-select

Once imported, let’s create the component. First, we import it:

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

After importing, let’s create the render function:

const Component = (props) => {
    // Create the categories array:
    var mainCategories = [
        { label: Science, value: 'science' },
        { label: Comic, value: 'comic' },
        { label: Education, value: 'education' },
        { label: History, value: 'historical' },
    ];

    // Add the component:
    return (
        
             console.log(value)}
                items={mainCategories}
            />
        
    );
};

export default Component;

It will appear as follows:

If we want to change the default text “Select an item…” displayed, we need to add the placeholder property and pass the object correctly with label and value:

    return (
        
             console.log(value)}
                placeholder={{ label: "Select a category", value: null }}
                items={mainCategories}
            />
        
    );

And it will appear as follows:

The selected value will be stored using the onValueChange property:

            onValueChange={(value) => console.log(value)}

Leave a Comment