Lawrence Eagles Senior full-stack developer, writer, and instructor.

How to use the react-native-picker-select

4 min read 1388

How to use the react-native-picker-select

Introduction

The react-native-picker-select is a React Native picker component that mimics the native select interface for Android and iOS.

Although it emulates the native select interface it allows developers to customize the interface as they see fit.

For iOS it, by default, just warps an unstyled TextInput component. The developer is allowed to pass down styles to customize its look and feel. However, for Android, the default picker is used by default.

Android users can force it to use an unstyled TextInput by passing false to the useNativeAndroidPickerStyle prop. Further customization can now be done by passing down styles.

react-native-picker-select is feature-packed and ships with lots of props which makes it very flexible and powerful. Let’s get started using it in the next section.

Getting started

As with all npm packages installation should be straightforward. However, react-native-picker-select comes with a gotcha especially if you use expo.

To install it, simply run:

npm i react-native-picker-select

That should work but sometimes you get the error below:

requireNativeComponent "RNCPicker" was not found in the UIManager error

You can resolve this error by running:

// React Native CLI
npm install @react-native-community/picker
npx pod-install

and

We made a custom demo for .
No really. Click here to check it out.

// Expo users
expo install @react-native-community/picker

Depending on your environment, running any of these commands would resolve the issue.
After installation cd into the app directory and run:

npm install or yarn install

This would install all the needed dependencies. Then run:

npm start or yarn start

This would start a development server for your application thus completing our development environment setup.

Once we have set up our environment, we can jump right into how to use the react-native-picker-select in detail.

Let’s do this in the next section.

Using the react-native-picker-select component

If you don’t want to go through the hassles of setting up a development environment, I have created a starter app for you.

Just clone it by running:

git clone https://github.com/lawrenceagles/react-native-picker-demo

cd into the app folder and start the app as already stated. We are greeted with a hello world and a select component as seen below.

hello world in metro bundler

The app above shows the most basic usage of the react-native-picker-select. Kindly consider the code below:

 import React from "react";
 import RNPickerSelect from "react-native-picker-select";
 import { StyleSheet, Text, View } from "react-native";
 export default function App () {
     return (
         <View style={styles.container}>
             <Text>Hello World!</Text>
             <RNPickerSelect
                 onValueChange={(value) => console.log(value)}
                 items={[
                     { label: "JavaScript", value: "JavaScript" },
                     { label: "TypeStript", value: "TypeStript" },
                     { label: "Python", value: "Python" },
                     { label: "Java", value: "Java" },
                     { label: "C++", value: "C++" },
                     { label: "C", value: "C" },
                 ]}
             />
         </View>
     );
 }
 const styles = StyleSheet.create({
     container : {
         flex            : 1,
         backgroundColor : "#fff",
         alignItems      : "center",
         justifyContent  : "center",
     },
 });

To work with the react-native-picker-select, we must import the RNPickerSelect component:

import RNPickerSelect from "react-native-picker-select";

This component is then reused in our code to render the select view. It has a myriad of props and two of them are required.

The required props are:

items props:

[
    { label: "JavaScript", value: "JavaScript" },
    { label: "TypeStript", value: "TypeStript" },
    { label: "Python", value: "Python" },
    { label: "Java", value: "Java" },
    { label: "C++", value: "C++" },
    { label: "C", value: "C" },
]

This is an array of objects. Each item is an object with a label and value property. The items appear as the options rendered to the user when the select component is clicked.

Consider the image below:

select component clicked

The onValueChange prop:

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

This is a callback function that returns the selected value and its index. This is useful as we can do a lot of work with the data returned from this callback.

Right now we are just logging the selected value to the console. But there are patterns to do some very interesting things with that data.

A typical pattern is to set state with the selected data as shown in the code below:

onValueChange={(value) => setState(value)}

This makes for some very powerful patterns; consequently, we can upgrade our example above:

import React, { useState } from "react";
import RNPickerSelect from "react-native-picker-select";
import { StyleSheet, Text, View } from "react-native";
export default function App () {
    const [ language, setLanguage ] = useState("");
    return (
        <View style={styles.container}>
            <Text>
                {language ?
                  `My favourite language is ${language}` :
                    "Please select a language"
                }
            </Text>
            <RNPickerSelect
                onValueChange={(language) => setLanguage(language)}
                items={[
                    { label: "JavaScript", value: "JavaScript" },
                    { label: "TypeStript", value: "TypeStript" },
                    { label: "Python", value: "Python" },
                    { label: "Java", value: "Java" },
                    { label: "C++", value: "C++" },
                    { label: "C", value: "C" },
                ]}
            />
        </View>
    );
}

Above we are able to get the selected value from the onValueChange callback function. Within which we store it in the language state as the current language:

onValueChange={(language) => setLanguage(language)}

The current language is then displayed to the user. However, if no language is selected a default text is rendered to the user:

<Text>
  {language ? `My favourite language is ${language}` : "Please select a language"}
</Text>

Consider the image below:

The upgraded app with setState

There are other optional props but for basic usage, the two above are required. Let’s look at some notable optional props.

The placeholder prop:

Consider the image below:the placeholder prop

Before any item is selected we see the select an item… default value displayed in the select component. This is the placeholder prop in action.

It is an object with both a label and a value property. However, the value of this object is null and the value of the label is "select an item..." as seen below:

{label: "select an item...", value: null } // the placeholder prop

We make our app more interactive by passing it a custom placeholder object like this:

<View style={styles.container}>
  <Text>Hello World!</Text>
  <RNPickerSelect
      placeholder={{ label: "Select you favourite language", value: null }}
      onValueChange={(value) => console.log(value)}
      items={[
          { label: "JavaScript", value: "JavaScript" },
          { label: "TypeStript", value: "TypeStript" },
          { label: "Python", value: "Python" },
          { label: "Java", value: "Java" },
          { label: "C++", value: "C++" },
          { label: "C", value: "C" },
      ]}
  />
</View>

This displays a more appropriate message to our users.
new select component

You disable the placeholder completely. If you would like to do that you can pass an empty object:

placeholder={{}} // disables the placeholder message

The useNativeAndroidPickerStyle prop

This is an Android-only prop, it is specific for Android devices. It takes a boolean value like we talked about earlier in our discourse.

By default, react-native-picker-select emulates the native Android select. To prevent this we can pass false to this prop. This forces the rendered select component to use an unstyled TextInput. Thereby, making it behave more like its iOS counterpart by default.

Consider the code and image below:

<View style={styles.container}>
  <Text>Hello World!</Text>
  <RNPickerSelect
      onValueChange={(value) => console.log(value)}
      useNativeAndroidPickerStyle={false}
      placeholder={{ label: "Select your favourite language", value: null }}
      items={[
          { label: "JavaScript", value: "JavaScript" },
          { label: "TypeStript", value: "TypeStript" },
          { label: "Python", value: "Python" },
          { label: "Java", value: "Java" },
          { label: "C++", value: "C++" },
          { label: "C", value: "C" },
      ]}
  />
</View>

react-native-picker-select with useNativeAndroidPickerStyle set to false.

You can get more details on all props here.

Styling

react-native-picker-select features sundry properties that can be targeted for styling. All of these must be nested under the style prop. Some of these properties are Platform specific. You can style the select component for both iOS and Android devices by targeting the inputIOS and inputAndroid properties respectively.

Consider the code:

const customPickerStyles = StyleSheet.create({
  inputIOS: {
    fontSize: 14,
    paddingVertical: 10,
    paddingHorizontal: 12,
    borderWidth: 1,
    borderColor: 'green',
    borderRadius: 8,
    color: 'black',
    paddingRight: 30, // to ensure the text is never behind the icon
  },
  inputAndroid: {
    fontSize: 14,
    paddingHorizontal: 10,
    paddingVertical: 8,
    borderWidth: 1,
    borderColor: 'blue',
    borderRadius: 8,
    color: 'black',
    paddingRight: 30, // to ensure the text is never behind the icon
  },
});

This works but because iOS select component uses wraps around unstyled TextInput by default, it provides a lot more style objects than the Android select component.

Style objects such as inputAndroidContainer, inputAndroid, and placeholder are not available by default for the Android platform.

However, this can be enabled by passing false to the useNativeAndroidPickerStyle.

You can get more details on styling here.

Also, you can see more styling implementations here.

Final thoughts

The react-naive-picker-select is a very powerful and easy to use React Native component.

Although it is not a full-blown form handling component, it is great at what it does. And it can make implementing select fields in our React Native applications an easy and fun task.

I do hope you enjoyed this discourse. And If you need more information on this awesome component, kindly visit their documentation.

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Lawrence Eagles Senior full-stack developer, writer, and instructor.

One Reply to “How to use the react-native-picker-select”

  1. Hi, my picker don’t even show anything – just an arrow at the end and nothing!!!!
    No placeholder, if I press it nothing happens.
    Help me here!

Leave a Reply