Component reusability is a foundational feature of building apps with React. Often same components are rendered multiple times, and we need the attribute to uniquely identify every instance. key 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 elements with different values. span key <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 event handler to access the element’s every time its clicked. onClick key We need to pass the event as a callback function, so it runs when the event happens, not every time the element (or component) is rendered. only In the function we simply element’s key. These elements are not dynamic, so we need to manually pass the as argument for each event handler. console.log() key <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 of clicked elements in React. However, most of the time, you need to get key of dynamically rendered components (and elements). key It’s common to render components based on an array in React. Usually we use 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. map() 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 method to create elements for every city in the array. Each string is used as text content for elements. map() <span> cities <span> Callback function inside the method has two arguments. First argument stands for item in the array. By default, the method also accepts second argument , which is the index of each item in the array. map city map() index We use this to give unique values to elements. event handler also takes the number and updates the state variable. index key <span> onClick index key Inside JSX, we render the state variable to show the element that was clicked. key If you liked this guide, consider checking out my . blog about React