Get the key index of an Element on click in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# 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

The code for this article is available on GitHub

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.

The code for this article is available on GitHub

I've also written a detailed guide on how to pass an event and parameter onClick.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.