Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate onClick event for parent and child element

I have JSX code like this:

<div id="parent" onClick={clickOnParent} style={{ width: 100, height: 100 }}>
  <div id="child" onClick={clickOnChild} style={{ width: 20, height: 20 }} />
</div>

When I click on parent (outside the child) it will run clickOnParent, and when I click the child it will run both clickOnParent and clickOnChild of course.
Now I want to trigger only clickOnChild and ignore clickOnParent when clicking exactly on the child. How can I do?

like image 466
Danny Avatar asked Oct 30 '25 04:10

Danny


1 Answers

Use Event.stopPropagation()

const clickOnChild = (event) => {
  event.stopPropagation();
  ...
}
like image 195
wangdev87 Avatar answered Oct 31 '25 18:10

wangdev87



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!