How to display dropdown in ReactNative?

React NativeJavascriptMobile Development

The React native picker component is similar to a dropdown that allows you to select a value from the multiple options given.

The basic Picker component is as follows −

<Picker selectedValue = {selectedelement} onValueChange = {updatefunc}>
   <Picker.Item label = "ItemLabel" value = "ItemValue" />
      ...
      ...
      ...
   <Picker.Item label = "ItemLabel" value = "ItemValue" />
</Picker>

To work with picker component, you need to import it first from react-native as follows −

import { Picker } from 'react-native'

Picker Properties

Sr.NoProps & Description
1enabled
It takes a boolean value. The picker will be disabled if set to false and the user will not be able to select the item.
2itemStyle
Styling to be applied for the items.
3mode
This property decides how to display the items of the picker. The options available are : dialog and dropdown. If dialog mode the picker items will be displayed in a modal dialog. If dropdown it will display like normal dropdown mode.
4onValueChange
The callback function that will get called when the item from the picker is selected. The parameters available are itemValue i.e the actual value selected and itemPosition i.e the index position of the item.
5selectedValue
The selected value from the picker.

Example: Display of Dropdown using Picker in ReactNative

This example shows the dropdown using the Picker component.

The code is as follows −

<Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
      <Picker.Item label = "Steve" value = "steve" />
      <Picker.Item label = "Ellen" value = "ellen" />
      <Picker.Item label = "Maria" value = "maria" />
   </Picker>

There are 3 values given to the Picker Steve, Ellen and Maria. Here is a complete code to display it.

import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet } from 'react-native'
class PickerExample extends Component {
   state = {user: ''}
   updateUser = (user) => {
      this.setState({ user: user })
   }
   render() {
      return (
         <View>
            <Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
            <Picker.Item label = "Steve" value = "steve" />
            <Picker.Item label = "Ellen" value = "ellen" />
            <Picker.Item label = "Maria" value = "maria" />
         </Picker>
         <Text style = {styles.text}>{this.state.user}</Text>
            </View>
         )
      }
   }
   export default PickerExample
   const styles = StyleSheet.create({
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'red'
   }
})

The this.state.user is used for picker control. The updateUser function will be triggered when a user is picked.

Output

When you open the name from picker you should see as below −

raja
Published on 01-Jul-2021 08:33:48
Advertisements