skip to Main Content
<div onClick={()=>do_stuff()}>
  <div classname="div-1"></div>
  <div classname="div-2"></div>
  <div classname="div-3"></div>
  <div classname="div-4"></div>
  <div classname="div-5"></div>
</div>

When the parent is clicked, it should only call the callback if for example, the click did not include div-4, div-5 etc.

How to implement this in React?

2

Answers


  1. You could check event.target with Element#matches.

    function do_stuff(event) {
      if (!event.target.matches('.div-4, .div-5')) {
        console.log('click');
      }
    }
    
    <div onClick={do_stuff}>
        { /* ... */ }
    </div>
    
    Login or Signup to reply.
  2. event.stopPropogation() solves this very easily.

    <div onClick={()=>do_stuff()}>
      <div classname="div-1"></div>
      <div classname="div-2"></div>
      <div classname="div-3"></div>
      <div classname="div-4" onClick={(event) => event.stopPropogation()}></div>
      <div classname="div-5" onClick={(event) => event.stopPropogation()}></div>
    </div>
    

    With nested HTML elements, click events work their way up the heirarchy. Child components have their onclicks fire first. Parent components onclicks fire after. Doesn’t matter how deeply nested the elements are, click events will always fire at the lowest nested level first, eventually ‘propogating’ all the way back up. You can stop the clicks from ‘propogating’ any further up by calling stopPropogation(). Once the callback with the stop propogation is executed, the rest of the call stack is simply erased.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search