React-Native Picker
Syntax
The
import React, { useState } from 'react';
import { View, Picker } from 'react-native';
function SelectColor() {
const [selectedColor, setSelectedColor] = useState('blue');
return (
<View>
<Picker
selectedValue={selectedColor}
onValueChange={(itemValue, itemIndex) => setSelectedColor(itemValue)}
>
<Picker.Item label="Blue" value="blue" />
<Picker.Item label="Green" value="green" />
<Picker.Item label="Red" value="red" />
</Picker>
</View>
);
}
export default SelectColor;
Example
import React, { useState } from 'react';
import { View, Text, Picker } from 'react-native';
function SelectColor() {
const [selectedColor, setSelectedColor] = useState('blue');
return (
<View>
<Text style={{ fontSize: 20, fontWeight: 'bold' }}>Select a color:</Text>
<Picker
selectedValue={selectedColor}
style={{ height: 50, width: 150 }}
onValueChange={(itemValue, itemIndex) => setSelectedColor(itemValue)}
>
<Picker.Item label="Blue" value="blue" />
<Picker.Item label="Green" value="green" />
<Picker.Item label="Red" value="red" />
</Picker>
<Text style={{ fontSize: 20 }}>You selected: {selectedColor}</Text>
</View>
);
}
export default SelectColor;
Output
The selected color will be displayed in the app as soon as the user selects an option from the dropdown.
Explanation
The
The selectedValue
prop specifies the value that should be selected by default, while the onValueChange
prop specifies the change event handler.
Inside the
Use
Important Points
selectedValue
prop must be set to match one of thevalue
props of the <Picker.Item> components.- The
onValueChange
prop is triggered whenever a new value is selected from the dropdown. - The
component is only available on iOS and Android platforms.
Summary
The selectedValue
and onValueChange
props, we can provide a simple and intuitive user experience.