Last updated: Apr 6, 2024
Reading time·2 min

To get the key index of an element on click in React:
onClick event listener to each element.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;

We used the Array.map() method to render the elements in the array.
We added an onClick event handler on each element.
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.
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.
I've also written a detailed guide on how to pass an event and parameter onClick.