react-native-picker-select
react-native-picker-select copied to clipboard
How to set value initially?
Describe the bug
I'm using this module it is working fine. I need to show value by default which is getting from API.
To Reproduce
I am using value prop but it's not working.
Expected behavior
How can i show value by default. What is the prop?
Additional details
- Device: All
- OS: All
- react-native-picker-select version: 9.0.0
- react-native version: 0.72.6
Reproduction and/or code sample
const [homebuild, setHomeBuild] = useState("");
const picker = useRef<RNPickerSelect>(null);
useEffect(() => {
picker.current?.setState({ homebuild: { value: propertyBuildOnYear, label: propertyBuildOnYear.toString(), } });
}, [])
<RNPickerSelect
ref={picker}
placeholder={{
label: "Home was build in *",
value: null,
}}
onValueChange={(value) => {
Keyboard.dismiss();
setHomeBuild(value)
}}
items={yearsList}
style={{
...pickerSelectStyles,
}}
// value={homebuild}
useNativeAndroidPickerStyle={false}
Icon={() => {
return <Image source={icon.dropdownIcon} style={{ ...styles.dropdownIconStyle, tintColor: "grey" }} />;
}}
/>
I've added the value and key prop in RNPickerSelect. The value was shown by default. But when i try to edit the Picker value, it was resetting for the first time. How can i fix this issue?
Code:-
const picker = useRef<RNPickerSelect>(null);
useEffect(() => {
const {
propertyBuildOnYear,
} = route?.params?.property;
setHomeBuild({ value: propertyBuildOnYear, label: propertyBuildOnYear.toString(), })
picker.current?.setState({ value: propertyBuildOnYear, label: propertyBuildOnYear.toString() });
}, [])
<RNPickerSelect
placeholder={{
label: "Home purchased in *",
value: null,
color: colors.defaultTxtColor,
fontFamily: fontFamilyType.HND.Regular,
}}
onValueChange={(value) => {
Keyboard.dismiss();
setHomePurchage(value)
}}
key={homepurchage.value}
value={homepurchage.value}
items={yearsList}
style={{
...pickerSelectStyles,
placeholder: {
color: colors.defaultTxtColor,
fontSize: scaler(16),
fontFamily: fontFamilyType.HND.Regular
},
iconContainer: {
top: 15,
right: 15,
},
}}
useNativeAndroidPickerStyle={false}
Icon={() => {
return <Image source={icon.dropdownIcon} style={{ ...styles.dropdownIconStyle, tintColor: "grey" }} />;
}}
/>
Screen recording:-
https://github.com/lawnstarter/react-native-picker-select/assets/146079306/8187d1fb-0b2e-45eb-a9fc-2c81a825ecff
I had the same problem with a form, everytime I changed a field, the select was reset to the initial value.
The solution is to update the variable you used in 'value' , in the onValueChange
const [defaultV, setDefaultV] = useState();
return (
<View>
<RNPickerSelect
items={data}
value={defaultV}
onValueChange={(value) => {
setDefaultV(value);
}}
/>
</View>
);