Home > front end >  Ignore click if focus is on button in element
Ignore click if focus is on button in element

Time:10-24

There is a problem, I have a clickable element and if I want to click on a button in the element, then both of them will work, when I need only the button to work. Implementation via ReactJS. Button position absolute in element! Code example:

 <div onClick={() => alert(1)}>
    ...content
    <button onClick={() => alert(2)}>Click me!</button>
</div>

CodePudding user response:

When you have a clickable element inside a clickable element, then you need to use event.stopPropagation();

So here

const myMethod = event => {
  alert(2);
  event.stopPropagation();
}

 <div onClick={() => alert(1)}>
    ...content
    <button onClick={myMethod}>Click me!</button>
</div>

CodePudding user response:

<div onClick={() => alert(1)}>
    <button onClick={(e) => {
        e.stopPropagation();
        alert(2)
    }}>Click me!</button>
</div>

CodePudding user response:

When the innermost component handles an event, and events bubble outwards. In React, the innermost element will first be able to handle the event, and then surrounding elements will then be able to handle it themselves.

More on this here

  • Related