Last updated: Apr 6, 2024
Reading time·2 min
To capture only parent's onClick event in React:
event.target
is equal to event.currentTarget
.const App = () => { const handleParentClick = event => { event.preventDefault(); if (event.target === event.currentTarget) { console.log('parent clicked'); // 👇 Your logic here } }; const handleChildClick = event => { console.log('child clicked'); }; return ( <div> <p onClick={handleParentClick}> Parent element <span style={{margin: '2rem'}} onClick={handleChildClick}> Child element </span> </p> </div> ); }; export default App;
We only want to run the logic in the handleParentClick
function when the
parent element is clicked, and not the child.
In the onClick
event handler of the parent, we had to compare the values of
event.target
and event.currentTarget
.
target
property on the event
gives us a reference to the element that triggered the event (the element that was clicked).On the other hand, the currentTarget
property on the event returns the element
that the event listener is attached to.
The event.currentTarget property always refers to the element to which the event handler has been attached, as opposed to Event.target which refers to the element on which the event occurs and which may be its descendant.
If your child element also has an event listener, you can use the Event.stopPropagation() method to prevent further propagation of the current event in the capturing and bubbling phases.
const App = () => { const handleParentClick = event => { event.preventDefault(); console.log('parent clicked'); }; const handleChildClick = event => { // 👇️ Stop event propagation (won't trigger parent's onClick) event.stopPropagation(); console.log('child clicked'); }; return ( <div> <p onClick={handleParentClick}> Parent element <span style={{margin: '2rem'}} onClick={handleChildClick}> Child element </span> </p> </div> ); }; export default App;
We used the stopPropagation()
method in the onClick
event handler of the
child element. This means that the parent's onClick
event won't get triggered
when the child element is clicked.
By default, when the onClick
event of the child element is triggered, the
event on the parent element would also get triggered, but the
stopPropagation()
method prevents this behavior.
I've also written a detailed guide on how to call a child function from a parent component in React.