How to get Key index of clicked Element in React? (Quick Solution)

November 12, 2023
React Js
How to get Key index of clicked Element in React? (Quick Solution)

It is very common that you need to get the index of the clicked Element in React. In this article, we will help you understand that and provide a solution to that problem.

Understanding the Problem:

We often use the map function to create React elements based on the data. Each element in the array should have a unique identifier, often called a “key.”

When one of these elements is clicked, you might need to know its index in the array to perform certain action.

Here’s a simple example of a component rendering a list of items:

function App() {
  const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);

  const handleItemClick = () => {

  };

  return (
    <div>
      <h1>Clickable List</h1>
      {items.map((item, index) => (
      <div items={items} onClick={()=>{handleItemClick()}} > List 1</div>
      ))}
    </div>
  );
}

How to get key index of clicked Element in React?

Now looking at the above code, you can see map is already providing us the index, we can pass this index to the function which in our case ishandleItemClick.

Here is how the final code will look like:

function App() {
  const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);

  const handleItemClick = (index) => {
    console.log('Clicked item at index:', index);
    // Do whatever you need with the index
  };

  return (
    <div>
      <h1>Clickable List</h1>
      {items.map((item, index) => (
      <div items={items} onClick={()=>{handleItemClick(index)}} > List 1</div>
      ))}
    </div>
  );
}

In the above code, you can see that we have wrapped the handleItemClick to be arrow function to pass the index,because it will not allow you to pass any parameters to that function without wrapping to the arrow function.

With the above code, you will able to get the key index of the clicked element in react.

Conclusion

In the above article, hope you have learned getting the key index of a clicked element in a React application involves passing the index as a parameter to the click event handler inside the arrow function.

This is a fundamental pattern when working with dynamic lists in React, and it allows you to perform actions based on the clicked element’s position in the array.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon