DEV Community

Note to myself
Note to myself

Posted on

Prevent onClick event on clicking child component

On situations when you want to trigger an onClick event when you click on a box but you have an input inside of it. In this case you will trigger the onClick event whenever you are willing to type in any input.
To prevent this write a function to stop propagation and add it to the child(input).

  function handleClicked {
    // Do something.
  }
  function stopPropagation(e) {
    e.stopPropagation();
  }

  return (
    <div>
      <div onClick={handleClicked}>
        <input onClick={stopPropagation} />
      </div>
    </div>
  );
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jcubic profile image
Jakub T. Jankiewicz

You have syntax error in first function - no parentheses.