Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Key Index on Click ES6 React

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 ?

like image 322
Nicc Avatar asked Oct 14 '16 13:10

Nicc


People also ask

How do you get the key on onClick 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.

How do you get the clicked element in React?

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 .

How do you pass parameters on onClick React?

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 .

How do I show text onClick in React?

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.


2 Answers

Use an arrow function.

onClick={() => handler(index)} 
like image 77
Radio- Avatar answered Sep 20 '22 14:09

Radio-


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>     ); } 
like image 31
Salman Momin Avatar answered Sep 17 '22 14:09

Salman Momin