I want to get option's value and key when select onChange
.
I know I can get option's value simplicity used event.target.value
in onChangeOption
function, but how can I get key
?
<select onChange={this.onChangeOption} value={country}> {countryOptions.map((item, key) => <option key={key} value={item.value}> {item.name} </option> )} </select>
To get the key index of an element on click in React:Add an onClick event listener to each element. Every time an element is clicked, call the handler function passing it the event and the key index.
React's key prop gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, it keeps those components/DOM nodes around, even if all the props changed.
A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.
You will need to pass value in key as a different prop.
From docs:
Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:
Read: https://reactjs.org/docs/lists-and-keys.html
Passing key as a prop works obviously, but much quicker way could be to include the key as a custom attribute in your html.
class App extends React.Component { constructor(props) { super(props); this.onSelect = this.onSelect.bind(this); } onSelect(event) { const selectedIndex = event.target.options.selectedIndex; console.log(event.target.options[selectedIndex].getAttribute('data-key')); } render() { return ( <div> <select onChange = {this.onSelect}> <option key="1" data-key="1">One</option> <option key="2" data-key="2">Two</option> </select> </div> ); } } 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With