Reputation: 369
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>
Upvotes: 1
Views: 246
Reputation: 1074008
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>
Upvotes: 4