I have a div with a onClick handler and also buttons inside with onClick events. How do I prevent the buttons from firing the div onclick?

Viewed 573

Basically I have a list with members of your team. For every member there is an individual div, to select a member you click on the div. I have added an on click event handler on the div so that on click it selects that specific member and highlights it. I also have an edit button and a remove button inside the div for each member. However what is happening right now is that when you want to edit or remove a team member it also triggers the div onClick. I understand that this is expectd behaviour however I'm not sure how I can prevent the div onClick from firing when the buttons are clicked or how I can achieve the same 'look and feel' without putting the buttons in the div.

I want to keep the same look (a section for every teammember which can be clicked to select a team member) but I don't mind changing the structure of the div. I'm working in React if that matters.

2 Answers

Here's a simple example of how you stop the clicks bubbling up to the parent:

const Button = () => (
  <div
    onClick={() => {
      console.log("I won't trigger if you click the inside div");
    }}
  >
    <div
      onClick={event => {
        event.stopPropagation(); // <-- this stops the click going through to the parent div
        console.log('Thank you for clicking the inside div');
      }}
    >
      I'm Inside
    </div>
  </div>
);

Change the onClick to:

    onClick = (event) => {
        //event.target includes the specific element which was clicked.
        if(event.target.id == '<YOUR-DIV-ID>'){
        //handler
        }
    }
Related