1

In React app I have onClick listener on Header (handleToggle). Header has 4 elements, the last element is Edit with own onClick listener (edit). How can I remove from Edit element, the listener that is applied on Header (handleToggle) and keep only his own listener (edit)?

<div className="heading-panel" onClick={e => this.handleToggle(e)}>
  <h5>Name</h5>
  <h5>lastName</h5>
  <h5>Number</h5>
  <a onClick={() => this.edit()}>Edit</a>
</div>

1 Answer 1

4

You tell the Edit click handler to stop event propagation.

<a onClick={e => { e.stopPropagation(); return this.edit();}>Edit</a>

That does it in the anonymous handler, but you could pass the event object to this.edit and have it do it instead:

<a onClick={e => this.edit(e)}>Edit</a>

then

edit(e) {
    e.stopPropagation();
    // ...
}

Live Example:

class Example extends React.Component {
  edit(e) {
    if (this.props.stop) {
      e.stopPropagation();
    }
    console.log("edit");
  }
  handleToggle() {
    console.log("handleToggle");
  }
  render() {
    return <div className="heading-panel" onClick={e => this.handleToggle(e)}>
      <h5>Name</h5>
      <h5>lastName</h5>
      <h5>Number</h5>
      <a onClick={e => this.edit(e)}>Edit</a>
    </div>;
  }
}

ReactDOM.render(
  <div>
    <div>Doesn't Stop:</div>
    <Example stop={false} />
    <div>Stops:</div>
    <Example stop={true} />
  </div>,
  document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you T.J., your comment was very helpful.

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.