Get the key index of an Element on click in React

Borislav Hadzhiev

Last updated: Jan 15, 2023
2 min


# 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.
const App = () => { const arr = ['Austria', 'Belgium', 'Canada']; const handleClick = (event, key) => { console.log(; console.log('key index: ', key); }; return ( <div> {, 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 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.

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.