Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get "key" prop from React element (on change)?

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> 
like image 652
jimmy Avatar asked Nov 02 '17 08:11

jimmy


People also ask

How do you get key from element in React?

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.

Can I use key as a prop in React?

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.

Can props in React change?

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.


2 Answers

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

like image 73
Naisheel Verdhan Avatar answered Oct 01 '22 04:10

Naisheel Verdhan


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>
like image 28
Agney Avatar answered Oct 01 '22 04:10

Agney