Borislav Hadzhiev
Tue Apr 26 2022·2 min read
Photo by Mitchell Orr
To set an onClick
listener on a div
element in React:
onClick
prop on the div.div
as event.currentTarget
.const App = () => { const handleClick = event => { // 👇️ refers to the div element console.log(event.currentTarget); console.log('div clicked'); }; return ( <div> <div onClick={handleClick}>Hello world</div> </div> ); }; export default App;
We set the onClick
prop on the div
element, so every time the element is
clicked, the handleClick
function gets invoked.
handleClick
function, access the currentTarget
property on the event
object.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).
If you want to pass a parameter to the handleClick
function, set the onClick
prop to an inline arrow function.
const App = () => { const handleClick = (event, message) => { // 👇️ refers to the div element console.log(event.currentTarget); console.log(message); console.log('div clicked'); }; return ( <div> <div onClick={event => handleClick(event, 'hello')}>Hello world</div> </div> ); }; export default App;
Notice that we are passing a function to the onClick
prop and not the result
of calling one.
If you invoke the function when passing it to the onClick
prop, e.g.
onClick={handleClick()}
, it would get immediately called when the component
mounts.
You could use this approach to set the onClick
prop on any other element, e.g.
a button
, a span
, etc.