reactjsreact-nativepickerreact-native-picker-select

React Native Picker Select: How to auto-select an item but still be able to select others?


I'm using RNPickerSelect in my React Native app. I want to have three options: A B and C. I want A to be selected by default (like how USA is often selected by default in a picker list of countries). Here's what I tried:

<RNPickerSelect
  value={{label: 'A', value: 'A'}}
    items={[
      { label: 'A', value: 'A' },
      { label: 'B', value: 'B' },
      { label: 'C', value: 'C' },
    ]}
  onValueChange={value => {}}
/>

This does select A by default, but the problem is that it then doesn't allow you to select any other the others after.

How should I approach this?


Solution

  • First make a component state like

    class DropDown extends Component {
       constructor() {
          this.state = {
              dropdownValue: 'A'
          }
       }
       
       handleDropdownChange = (name) => (value) => {
          this.setState({ [name]: value })
       }
       
       render() {
          const { dropdownValue } = this.state  
    
          return (
             <RNPickerSelect
                value={dropdownValue}
                items={[
                  { label: 'A', value: 'A' },
                  { label: 'B', value: 'B' },
                  { label: 'C', value: 'C' },
                ]}
                onValueChange={this.handleDropdownChange('dropdownValue')}
             />
          )
       }
    }