Get the key index of an Element on click in React

avatar

Borislav Hadzhiev

Mon Apr 18 20221 min read

banner

Photo by Esther Ann

Get the key index of an Element on click in React #

To get the key index of an element on click in React:

  1. Add an onClick event listener to each element.
  2. Every time an element is clicked, call the handler function passing it the event and the key index.
App.js
const App = () => { const arr = ['Austria', 'Belgium', 'Canada']; const handleClick = (event, key) => { console.log(event.target); console.log('key index: ', key); }; return ( <div> {arr.map((element, key) => ( <div onClick={event => handleClick(event, key)} key={key}> {element} <hr /> </div> ))} </div> ); }; export default App;

get key index of element on click

We used the Array.map method to render the elements in the array.

We added an onClick event handler on each element.

The onClick prop on each div is set to a function that takes the event parameter and calls our handleClick function with the event and the key index passed as parameters.

We are able to access the key index as the second parameter in the handleClick function.

Notice that we are passing a function to the onClick prop of each div.

It's very important to pass a function to the prop, and not the result of calling a function.

If we pass the result of calling a function to the onClick prop, e.g. onClick={handleClick(key)}, then the handleClick function would get invoked immediately on page load.

This is often a cause of infinite re-render loops in React applications, especially when we change a component's state in the click handler function.

Use the search field on my Home Page to filter through my more than 1,000 articles.