29

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 ?

Obed Parlapiano
  • 3,226
  • 3
  • 21
  • 39
Nicc
  • 777
  • 3
  • 8
  • 19

7 Answers7

41

Use an arrow function.

onClick={() => handler(index)}
Radio-
  • 3,151
  • 21
  • 22
17

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>
    );
}
Salman Momin
  • 327
  • 2
  • 4
  • 2
    Why is this a better approach than the accepted answer above? – Hamund Mar 19 '19 at 08:45
  • 2
    @Hamund citation from google "If you use arrow functions within render , each call to render will create new function objects. If you then pass these functions to child elements via props , optimizations based on PureComponent or shouldComponentUpdate will fail (as the arrow function props will change on every render)." - So if you are into performance then it's better to pass a ref to a function instead of an arrow function. – Norfeldt Jul 31 '19 at 20:28
  • 1
    @SallyRothroat: this will not work because event.target can be any element inside
  • element.
  • – user2428804 Apr 03 '20 at 17:53
  • 3
    change to `currentTarget` – FDisk Aug 25 '20 at 13:12