React/js onClick on both the Parent div and Child div. Parent always fires

Viewed 2733

Hello i got a problem with having onClick on my parent and on its child that triggers which menuSection shows up. And even if i click on the child its the parents section that shows up. How to only trigger the child if that element gets clicked?

    <div> onClick={() => props.onClick(MenuSection.Default)} >
          <div <span><InfoIcon /></span> Some info</div>
          <div>More Info</div>
          <div>Even more Info</div>
          <div onClick={() => props.onClick(MenuSection.NotDefault)}><InfoIcon /></div>
    </div>

So here is how it looks and its always MenuSection.Default that shows up never MenuSection.NotDefault.

2 Answers

pass in e in the function and use

e.stopPropagation();

<div onClick={() => props.onClick(MenuSection.Default)} >
      <div <span><InfoIcon /></span> Some info</div>
      <div>More Info</div>
      <div>Even more Info</div>
      <div onClick={(e) => e.stopPropagation();props.onClick(MenuSection.NotDefault)}><InfoIcon /></div>
</div>

But I would also move the onClick inline function out of the render method and reference it with "this.nameOfClickMethod", nameOfClickMethod is of course to be named at your choise.

You can use event.stopPropagation(). It prevents the event from propagating.

<div> onClick={() => { props.onClick(MenuSection.Default)} } >
          <div <span><InfoIcon /></span> Some info</div>
          <div>More Info</div>
          <div>Even more Info</div>
          <div onClick={(e) => { e.stopPropagation();props.onClick(MenuSection.NotDefault)}}><InfoIcon /></div>
    </div>
Related