Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 266
Doo Doo Avatar asked Jun 04 '18 03:06

Doo Doo


People also ask

How do you style react native picker select?

The developer is allowed to pass down styles to customize its look and feel. However, for Android, the default picker is used by default. Android users can force it to use an unstyled TextInput by passing false to the useNativeAndroidPickerStyle prop. Further customization can now be done by passing down styles.


2 Answers

Use the index to get the array element.

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

    console.log(branches[index]);

  }
 );
}
like image 128
Naveen Vignesh Avatar answered Nov 15 '22 08:11

Naveen Vignesh


Finally I can fixed the problem now. I know it's not a good solution, but at least it worked as what I want now :)

constructor(props) {
  super(props);
  pickerSelected: '',
  defaultSelected: 'Select branch's name',
}

and here how I did to update my states

onPickerValueChange = (value) => {
    const { branches } = this.state;
    let branchName = branches.find(branch => branch.id === value);
    this.setState(
      {
        pickerSelected: value,
        defaultSelected: branchName.name
      }
    );
}

Hope this can help other people who meet the same problem :)

like image 43
Doo Doo Avatar answered Nov 15 '22 10:11

Doo Doo