Search code examples
react-nativepicker

How do I setState id when name is selected in the picker dropdown?


I have a json array in the below format

  this.state = {
    allTeachers: [
        {
            "id": "qKUd5GoBwpolnxM4upjo",
            "name": "XYZ",
            "subject": "Science"
        },
        {
            "id": "qaUe5GoBwkrtnxM4kOip",
            "name": "Vidya",
            "subject": "Mathematics"
        }
    ]
  }

And I am using the below code for dropdown. Now I am able to setState the name, but I want to show name in dropdown, and setstate the respective id of the name selected. I am using react-native picker. How can I do this?

<View style ={styles.dropdownInput}>
{
    <Picker
        selectedValue={this.state.teacher_name}
        style={styles.pickerCss}
        onValueChange={(itemValue, itemIndex) => this.setState({teacher_name: itemValue})}
    >
    <Picker.Item label='Select Teacher' value='0' />
    {
        this.state.allteachers ?
            this.state.allteachers.map((item,key) => (
                <Picker.Item label={item.name} value={item.name} />
            ))
        :
        false
    }
    </Picker>
}
</View>

Solution

  • You just need to set the PickerItem's value to the respective id. That means change:

    <Picker.Item label={item.name} value={item.name} />
    

    to

    <Picker.Item label={item.name} value={item.id} />
    

    Now

    onValueChange={(itemValue, itemIndex) => this.setState({teacher_name: itemValue})}
    

    stores the teacher_id in the teacher_name state variable. You could create a new state variable called teacher_id in your constructor and store the id there.

    In addition, I would recommend a small refactoring. Instead of:

    {
        // btw here is a typo your array is called allTeachers
        this.state.allteachers ?
            this.state.allteachers.map((item,key) => (
                <Picker.Item label={item.name} value={item.name} />
            ))
        :
        false
    }
    

    I would create a renderPickterItems function:

    renderPickerItems(allTeachers){
        if (allTeachers) {
           return(
            allTeachers.map((item,key) => (
            <Picker.Item label={item.name} value={item.id} />
            ))
        );
        }   
      }
    

    which you can call with:

     <Picker.Item label='Select Teacher' value='0' />
        {this.renderPickerItems(this.state.allTeachers)}
     </Picker>
    

    Complete Working Example:

    https://snack.expo.io/HJwLcXT6E