0

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>

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.