how to set inital value of React-Native Picker to empty
Asked Answered
B

3

11

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.

Berth answered 16/3, 2017 at 17:44 Comment(2)
it is not possible. you could create a additional item with label="" and empty value.Houdan
@TobiasLins even if I created a additional item with label="" , 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
C
5

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>
Crowning answered 12/3, 2019 at 10:39 Comment(0)
C
2

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>
Carangid answered 6/10, 2021 at 8:56 Comment(0)
O
0

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>
Overmatch answered 8/9, 2021 at 20:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.