Reacts select onChange get key

does anybody know how to retrieve the “key” value from a select when the function onChange is triggered?

callback(e) {
  e.target.value;
}
...
<select onChange={this.callback.bind(this)}>
    <option key={obj.id}>{obj.name}</option>
    <option key={obj.id}>{obj.name}</option>
</select>

I know I can get the value of obj.name with target.value but I can’t find out how to retreive the key.

Answer

You could set the id to a data attribute, then access it from e.target. A modified version of your example:

callback(e) {
  for (let node of e.target.children) {
    if (node.value === e.target.value) {
      console.log(node.getAttribute('data-id');
      return;
    }
  }
}
...
<select onChange={this.callback.bind(this)}>
    <option key={obj1.id} data-id={obj1.id} value={obj1.value}>{obj1.name}</option>
    <option key={obj2.id} data-id={obj2.id} value={obj2.value}>{obj2.name}</option>
</select>

Edit:

Modified above example to fix issue, since e.target actually refers to the select element, not the option element. You need to find the selected option then get its data-id attribute. Working example:

https://jsfiddle.net/69z2wepo/50706/

Leave a Reply

Your email address will not be published. Required fields are marked *