Doo Doo
Doo Doo

Reputation: 1347

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.

Upvotes: 7

Views: 9910

Answers (3)

guisszo 2.0
guisszo 2.0

Reputation: 19

Did you try to do something like that by making the value an object ??

Something that looks like this:

    <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={id: branch.id, name: branch.name}/>
    );
    })}
   </PickerIOS>

And access it with something like that :

this.setState(
      {
        pickerSelected: value.id,
        defaultSelected: value.name
      }
    );

Upvotes: 0

Doo Doo
Doo Doo

Reputation: 1347

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 :)

Upvotes: 1

Naveen Vignesh
Naveen Vignesh

Reputation: 1357

Use the index to get the array element.

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

    console.log(branches[index]);

  }
 );
}

Upvotes: 6

Related Questions