0

What is the proper way to handle an onClick event?

<div class='container' onClick={() => { *do something* }}>
  <div class='element'></div>
  <div class='element'></div>
  <div class='element'></div>
</div>

This will cause onClick to also trigger if you click on one of the child elements. How can I restrict the event to only fire on the container?

mowtheone
  • 511
  • 7
  • 18
  • A better javascript solution can be found here. https://stackoverflow.com/questions/9183381/how-to-have-click-event-only-fire-on-parent-div-not-children – Kavindra May 20 '18 at 11:59

2 Answers2

2

Check event.currentTarget.

<div class='container' onClick={(e) => { if(e.currentTarget.class == "container") { do something } }}>
  <div class='element'></div>
  <div class='element'></div>
  <div class='element'></div>
</div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

limit action to event target. sth like that.

document.querySelector('.container').addEventListener('click', function(e){
  e.target.doSomething;
});

/*
* document.querySelector('.container')
*   .addEventListener('click', (e) => {
*   e.target.doSomething;
*})
*/
marmeladze
  • 6,468
  • 3
  • 24
  • 45