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)
Hope this answer will help
1) First find selected index which is called key
var selectedIndex = event.target.options.selectedIndex;
2) If you have custom attribute and want to fetch value of that attribute then
var customAtrribute= event.target.options[selectedIndex].getAttribute('customAtrribute');
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>
Use react-select. It is able to handle id
and value
elegantly. Map your id
to react-select value
and your value
to react-select label
.
You can configure callback which will return you selected value/s. You can even turn on search.