Get the id of the element on Click in React

avatar

Borislav Hadzhiev

Last updated: Apr 26, 2022

banner

Photo from Unsplash

Get the id of the element on Click in React #

To get the id of the element on click in React:

  1. Set the onClick prop on the element to a function.
  2. Access the id of the element on the currentTarget property of the event.
  3. For example, event.currentTarget.id returns the element's id.
App.js
const App = () => { const handleClick = event => { console.log(event.currentTarget.id); }; return ( <div> <button id="my-btn" onClick={handleClick}> Click </button> </div> ); }; export default App;

get id of clicked element

We set the onClick prop on the button element, so every time the element is clicked, the handleClick function is invoked.

We used the currentTarget property on the event to get a reference to the button and get the value of its id prop.

The currentTarget property on the event gives us access the element that the event listener is attached to.

Whereas the target property on the event gives us a reference to the element that triggered the event (could be a descendant).

You can access the button element as event.currentTarget and access any of its properties.

Alternatively, you can set the ref prop on the element and get its id using the ref object.

App.js
import {useRef} from 'react'; const App = () => { const ref = useRef(null); const handleClick = event => { console.log(event.currentTarget.id); console.log(ref.current.id); }; return ( <div> <button ref={ref} id="my-btn" onClick={handleClick}> Click </button> </div> ); }; export default App;

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the button element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <button ref={myRef}>, React sets the .current property of the ref object to the corresponding DOM node.

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.