How To Get Key Clicked Element in React

Written by iraklitch | Published 2024/01/10
Tech Story Tags: react | component | react-components | event-handlers-in-react | key-clicked-element-in-react | key-clicked-element | component-reusability | key-of-clicked-elements

TLDROften same components are rendered multiple times, and we need the key attribute to uniquely identify every instance.via the TL;DR App

Component reusability is a foundational feature of building apps with React. Often same components are rendered multiple times, and we need the key attribute to uniquely identify every instance.

In this guide, we will learn how to get key of clicked elements in React.

Get key of clicked elements in React

For the sake of simplicity, let’s create a page with three span elements with different key values.

<div>
      <span key={1}>element one</span>
      <span key={2}>element two</span>
      <span key={3}>element three</span>
</div>

Now let’s set an onClick event handler to access the element’s key every time its clicked.

We need to pass the event as a callback function, so it runs only when the event happens, not every time the element (or component) is rendered.

In the function we simply console.log() element’s key. These elements are not dynamic, so we need to manually pass the key as argument for each event handler.

<div>
      <span key={1} onClick={() => console.log(1)}>
        element one
      </span>
      <span key={2} onClick={() => console.log(2)}>
        element two
      </span>
      <span key={3} onClick={() => console.log(3)}>
        element three
      </span>
    </div>

Get the key on click of dynamically rendered elements

Simple example from before is useful to demonstrate how to get key of clicked elements in React. However, most of the time, you need to get key of dynamically rendered components (and elements).

It’s common to render components based on an array in React. Usually we use map() method to return a component for every item in the array. Data from each item is used as contents, props, attributes, or even to apply custom styles to elements and components.

Let’s look at an example:

function Hello() {
  const [key, setKey] = useState(null);
  const cities = ["London", "Paris", "Rome"];
  return (
    <div>
      {cities.map((city, index) => (
        <span key={index} onClick={() => setKey(index)}>
          {city}
        </span>
      ))}
      <p>Clicked element's key is {key}</p>
    </div>
  );
}

We use the map() method to create <span> elements for every city in the cities array. Each string is used as text content for <span> elements.

Callback function inside the map method has two arguments. First argument city stands for item in the array. By default, the map() method also accepts second argument index, which is the index of each item in the array.

We use this index to give unique key values to <span> elements. onClick event handler also takes the index number and updates the key state variable.

Inside JSX, we render the state variable key to show the element that was clicked.

If you liked this guide, consider checking out my blog about React.


Written by iraklitch | Former front-end developer, and current writer who loves to help people understand difficult technical concepts.
Published by HackerNoon on 2024/01/10