In this post, we are going to look into building a picker system using @react-native-picker/picker package.
Earlier days, the react-native core component used to support a built-in Picker component, but it is now deprecated, and you should no longer import it into your code.
We are going to look into a new way to use the picker component using this component which is available in github repo.
Lets get started
Step 1. Installation
For Expo Projects:
If you are using Expo then just execute the command below to install the package:
expo install @react-native-picker/picker
For non-expo projects:
npm i @react-native-picker/picker
If you are developing an app for iOS, you need to perform an extra command:
npx pod-install
Step 2 : Example
Preview
To Add a picker
<Picker
selectedValue={gender}
onValueChange={(value, index) => setGender(value)}
mode="dropdown" // Android only
style={styles.picker}
>
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: '#F2F5FB'
},
headertext:{
fontSize:20,
color: '#000'
},
text: {
fontSize: 16,
color: '#000'
},
picker: {
marginVertical: 30,
width: 300,
padding: 10,
borderWidth: 1,
borderColor: "#fff",
color:"#000"
},
});
The Code
// App.js
import "react-native-gesture-handler";
import React, { useState } from "react";
import { View, Text, StyleSheet } from "react-native";
import { Picker } from "@react-native-picker/picker";
function App() {
const [gender, setGender] = useState('Unknown');
return (
<View style={styles.screen}>
<Text style={styles.headertext}>A Picker Demo by NintyZeros.com</Text>
<Picker
selectedValue={gender}
onValueChange={(value, index) => setGender(value)}
mode="dropdown" // Android only
style={styles.picker}
>
<Picker.Item label="Select Gender" value="Unknown" />
<Picker.Item label="Male" value="Male" />
<Picker.Item label="Female" value="Female" />
<Picker.Item label="Not Willing" value="NA" />
</Picker>
<Text style={styles.text}>You Selected: {gender}</Text>
</View>
);
}
export default App;
// Just some styles
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: '#F2F5FB'
},
headertext:{
fontSize:20,
color: '#000'
},
text: {
fontSize: 16,
color: '#000'
},
picker: {
marginVertical: 30,
width: 300,
padding: 10,
borderWidth: 1,
borderColor: "#fff",
color:"#000"
},
});
Common Props
Name | Platform | Description |
---|---|---|
onValueChange | Android, iOS | The callback function that fired when an item is selected |
selectedValue | Android, iOS | Value matching value of one of the items (string, integer) |
style | Android, iOS | Used for styling the picker |
testID | Android, iOS | Used for testing |
enabled | Android | Whether the picker is enabled or disabled |
mode | Android | “dialog” or “dropdown” |