MemoryLeak MemoryLeak - 8 days ago 4
React JSX Question

how to get the key of a selected value from a dropdown in reactjs?

how to bind a json data which has a key-value pair to select html in reactjs, such that It should display the value in the drop-down and If I choose a value , I should provide the relevant key?

For example:

var optionsdata = [
{key='101',value='Lion'},
{key='102',value='Giraffe'},
{key='103',value='Zebra'},
{key='104',value='Hippo'},
{key='105',value='Penguin'}
];


in the drop-down, it should show "Lion","Giraffe","Zebra",...
if I choose, Zebra, I should get the select value (Zebra) as well as the key (103, in the above example)

Answer

You can simply filter out the data from the your object once you get get the value of selected option. I have not used controlled input in my example, If you use that it will be even better.

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      optionsdata : [
         {key:'101',value:'Lion'},
         {key:'102',value:'Giraffe'},
         {key:'103',value:'Zebra'},
         {key:'104',value:'Hippo'},
         {key:'105',value:'Penguin'}
       ]
    }
  }
  handleChange = (e) => {
    console.log(e.target.value);
    var value = this.state.optionsdata.filter(function(item) {
      return item.key == e.target.value
    })
    console.log(value[0].value);
  }
  render() {
    return (
      <select onChange={this.handleChange}>
        {this.state.optionsdata.map(function(data, key){  return (
          <option key={key} value={data.key}>{data.value}</option> )
        })}
      </select>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"></script>
<div id="app"></div>

Comments