How to Create a Picker Component with Prompt Message in React Native

Last Updated on December 11, 2020.

If you want to create a picker component with prompt message in React Native then this is the right place to look for.

The Picker component will be removed from react native core and hence install Picker from react native community using the following command.

npm install @react-native-picker/picker --save

or

yarn add @react-native-picker/picker

For iOS users, execute the following command too.

npx pod-install

Creating a picker component with a prompt is pretty simple, all you need is to add prompt prop to the picker component and assign your message to it. Still, have doubts? just have a look at the example given below.

Class component

import React, {Component} from 'react';
import {View} from 'react-native';
import {Picker} from '@react-native-picker/picker';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      language: 'java',
    };
  }
  render() {
    return (
      <View>
        <Picker
          selectedValue={this.state.language}
          style={{height: 50, width: 100}}
          prompt="Choose Language"
          onValueChange={(itemValue, itemIndex) =>
            this.setState({language: itemValue})
          }>
          <Picker.Item label="Java" value="java" />
          <Picker.Item label="JavaScript" value="js" />
        </Picker>
      </View>
    );
  }
}

Function component

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

const App = () => {
  const [language, setlanguage] = useState('java');
  return (
    <View>
      <Picker
        selectedValue={language}
        style={{height: 50, width: 100}}
        prompt="Choose Language"
        onValueChange={(itemValue, itemIndex) => setlanguage(itemValue)}>
        <Picker.Item label="Java" value="java" />
        <Picker.Item label="JavaScript" value="js" />
      </Picker>
    </View>
  );
};

export default App;

Following is the output of the above example.

react native picker example

Leave a Reply

%d bloggers like this: