Reputation: 603
I'm trying to get the 'key' value of my dynamic dropdown list as follows:
searchSubmit(e){
const s = e.target.value;
alert(s);
}
my dropdown list is as follows:
<select
className="textboxstyle"
onChange={this.searchSubmit}
>
<option key='-1'>Select Brand</option>
<option key='0'>ALL</option>
{optionItems}
</select>
And my dynamic drop-down is populated as follows,
let brands = this.state.brands;
let optionItems = brands.map((brand) =>
<option key={brand.id}>{brand.name}</option>
);
But when I select option, alert display the name of the selected value, not the key. How to get the 'key' value? Thanks
Upvotes: 1
Views: 5614
Reputation: 112797
The key
prop is used by React to differentiate between all the elements in an array. If you want value
to be the id
of the brand
, you can use it as value
as well as key
.
Example
class App extends React.Component {
state = {
brands: [{ id: 1, name: "Foo" }, { id: 2, name: "Bar" }]
};
searchSubmit = e => {
const { value } = e.target;
alert(value);
};
render() {
const { brands } = this.state;
return (
<select onChange={this.searchSubmit}>
<option value="-1">Select Brand</option>
<option value="0">ALL</option>
{brands.map(brand => (
<option value={brand.id} key={brand.id}>
{brand.name}
</option>
))}
</select>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Upvotes: 2