How to get value and label name from React Native Picker?

Doo Doo picture Doo Doo · Jun 4, 2018 · Viewed 7.8k times · Source

In my react native project, I have a picker that allow user to filter staffs by branch. I got the label name and value from my database. Now I can got branch id from picker value and able to filter staffs by branch with this link http://192.168.10.60:8888/customerfeedback/public/api/staff?pId=.

My problem is that I want to update my state value to show user which branch they have selected instead of display id. How can I get picker label name and update it to my state?

Here is my code:

    <PickerIOS
     style={{ flex: 1 }}
     selectedValue={this.state.pickerSelected}
     onValueChange={(value, index) => this.onPickerValueChange(value, index)}
    >
    {branches.map(branch =>{
      return (
         <PickerIOS.Item key={branch.id} label={branch.name} value={branch.id}/>
    );
    })}
   </PickerIOS>

Now I can get the value and index, but I want to get index from my database instead of array index.

onPickerValueChange = (value, index) => {
    this.setState(
      {
        pickerSelected: value
      },
      () => {

        console.log(value, index);

      }
    );
}

Thank for help.

Answer

Naveen Vignesh picture Naveen Vignesh · Jun 4, 2018

Use the index to get the array element.

onPickerValueChange = (value, index) => {
this.setState(
  {
    pickerSelected: value
  },
  (name, index) => {

    console.log(branches[index]);

  }
 );
}