Last updated: Apr 7, 2024
Reading time·2 min
To get the id of the element on click in React:
onClick
prop on the element to a function.id
of the element on the currentTarget
property of the
event
.event.currentTarget.id
returns the element's id
.const App = () => { const handleClick = event => { console.log(event.currentTarget.id); }; return ( <div> <button id="my-btn" onClick={handleClick}> Click </button> </div> ); }; export default App;
We set the onClick
prop on the button element, so every time the element is
clicked, the handleClick
function is invoked.
<button id="my-btn" onClick={handleClick}> Click </button>
currentTarget
property on the event
to get a reference to the button
and get the value of its id
prop.const handleClick = event => { console.log(event.currentTarget.id); };
The currentTarget
property on the event gives us access to 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.
ref
To get the id of an element on click using a ref
:
useRef
hook to create a ref
object.ref
prop on the element.onClick
prop on the element.id
of the element as ref.current.id
.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.
const ref = useRef(null);
The hook returns a mutable ref object whose .current
property is initialized
to the passed argument.
current
property on the ref object to get access to the button
element on which we set the ref
prop.const handleClick = event => { console.log(event.currentTarget.id); console.log(ref.current.id); };
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.