Get Key Index on Click ES6 React

ghz 6months ago ⋅ 65 views

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 ?

Answers

To get the index of the <li> element clicked without explicitly binding this in ES6, you can use an arrow function for your click handler. Arrow functions automatically capture the this value of the enclosing context, so you don't need to worry about binding this. Here's how you can modify your list component:

const List = (props) => {

  const handleClick = (index) => {
    // Handle click logic here, using 'index'
    console.log('Clicked index:', index);
  };

  const listItems = props.items.map((item, index) => (
    <li key={index} onClick={() => handleClick(index)}>
      {item.text}
    </li>
  ));

  return (
    <div>
      <ul>
        {listItems}
      </ul>
    </div>
  );
};

export default List;

Explanation:

  1. Arrow Function in onClick:

    • Instead of defining handler as a function expression inside map(), you define handleClick as an arrow function outside of map().
    • handleClick accepts index as an argument, which represents the index of the clicked <li> element.
  2. Passing Index to handleClick:

    • In the onClick attribute of each <li>, you invoke handleClick with index as an argument.
    • The arrow function in onClick={() => handleClick(index)} ensures that handleClick is called with the correct index when the <li> is clicked.
  3. No Binding Needed:

    • Since handleClick is an arrow function, it inherits the lexical this context from its surrounding scope (in this case, List component).
    • Arrow functions do not have their own this binding, so you avoid issues related to this context in event handlers.

Note:

  • Make sure to capitalize your component name (List instead of list) to follow React component naming conventions.
  • This approach simplifies handling events in React components without the need for explicit binding or separate handler functions for each list item. Each <li> element will correctly log its index when clicked.