I have the following component
const list = (props) => { const handler = function(){ }; var listItems = props.items.map(function(item, index){ return ( <li key={index} onClick={ handler }> {item.text} </li> ) }); return ( <div> <ul> {listItems} </ul> </div> ) }
On Click i'd like to get the index of the li clicked. Using ES6 and without binding how can i do this ?
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.
To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .
To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .
If you want to display it in an alert window, you need to call a function to trigger the window. However, if you need to show the message in your render, you can use a state to manage that. If you need to toggle the text on button click, you just need to update the onButtonClickHandler function to this.
Use an arrow function.
onClick={() => handler(index)}
You can actually get index without using an arrow function. The only thing you need to do is pass the index as an attribute and get that value from the event as e.target.getAttribute("your_attribute_name")
const list = (props) => { const handler = function(e){ console.log(e.target.getAttribute("data-index")); //will log the index of the clicked item }; var listItems = props.items.map(function(item, index){ return ( <li key={index} data-index={index} onClick={ handler }> {item.text} </li> ) }); return ( <div> <ul> {listItems} </ul> </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