Do you know how to set the inital value of React-Native Picker component to empty. I mean it should not show any item selected.
how to set inital value of React-Native Picker to empty
Asked Answered
I solved this problem by setting fake unselectable item with value={-1}
. Then when user picks valid item,fake item with value={-1}
disappear.
// this.state.selectedIndex initially setted to -1
<Picker
selectedValue={this.state.selectedIndex}
onValueChange={(value, index) => { this.setState({selectedIndex: index})
}}
>
// first fake item
if(Platform.OS === 'android' && this.state.selectedIndex === -1) {
<Picker.Item label={'CANCEL'} value={-1} />
}
<Picker.Item label={'First'} value={1} />
<Picker.Item label={'Second'} value={2} />
<Picker.Item label={'Third'} value={3} />
</Picker>
I think the part you need is enabled={false}
.
https://github.com/react-native-picker/picker#enabled-1
<Picker
selectedValue={selected}
onValueChange={(itemValue, itemIndex) => setSelected(itemValue)}>
<Picker.Item key='' label='-- Select a Item --' value={null} enabled={false} />
{items.map(i => <Picker.Item key={i.key} label={i.label} value={i.value} />)}
</Picker>
you can do it this way
<Picker
selectedValue={selected}
onValueChange={itemValue => setSelected(itemValue)}
>
{items &&
items.map((element, index) => {
if (index === 0) {
return (
<Picker.Item
key={element.value}
label={element.label}
value={element.value}
enabled={false}
/>
);
}
return (
<Picker.Item
key={element.value}
label={element.label}
value={element.value}
/>
);
})}
</Picker>
© 2022 - 2024 — McMap. All rights reserved.
label=""
and empty value. – Houdanlabel=""
, user can able to select that, I want that there is no inital value nor users can able to reselect that additional item and show something like placeholder. – Syllogize