Stop onClick events propagating to children

By January 18, 2020Uncategorized

Sometimes in React I may want to build a clickable component like a button but have an SVG or some other more complicated content like some divs.

<Button onClick={doSomething()}>
  <div>
    <div>Left</div>
    <div>Right</>
  </div>
</Button>

In this instance, I want the onClick event to work at the button level, and not when it’s children are clicked.

As it is, the onClick event would be fired when any of the children are clicked. To prevent this, you can simply add a no pointer events CSS property to the child elements.

pointer-events: none;

This will prevent the children from firing off an uncontrolled click event and possibly breaking your code.