How do you get a button in DIV not call the <div> click event

Viewed 59

I have a which has it own onClick() event. I want the user to be able to click anywhere in the div to perform an action (flipping the card over). However, there is also a button in that DIV as well. For the button, I do not want it to call the div's onClick() (so don't flip card over).

<div onClick={this.handleClick}>
    <button onClick={this.buttonClickEvent}>menu</button>
</div>

Any idea on how to perform this?

2 Answers

You can use stopPropagation() method. It prevents further propagation of the current event in the capturing and bubbling phases. So, your buttonClickEvent will look like this:

  buttonClickEvent = (e) => {
    // do smth here
    e.stopPropagation();
  }

Try using stopPropagation() with IDs

const div = document.querySelector('#div');
const btn = document.querySelector('#btn');

div.addEventListener('click', (e) => {
  // do something here
  e.stopPropagation();
  console.log('div');
});

btn.addEventListener('click', (e) => {
  // do something here
  e.stopPropagation();
  console.log('button');
});
#div {
  background-color: red;
  width: 100px;
  height: 100px;
  display: grid;
  place-items: center;
}
<div id="div">
  div
  <button id="btn">menu</button> div
</div>

Related