Reputation: 111
Consider the following React component
export default function App() {
return (
<div className="App" onClick={() => console.log("on app div")}>
<div className="first" onClick={() => console.log("first div")}>
first
</div>
<div className="second" onClick={() => console.log("second div")}>
second
</div>
<div className="third">third</div>
</div>
);
}
So, a click on child div's will currently trigger onClick methods of both parent and child div's. But for the first child I would like only child onClick method to be triggered. Is there a way to do this?
I've tried giving the child div a higher z-index value but it's still triggering both onClicks, here is the css I've tried
.App {
font-family: sans-serif;
text-align: center;
position: relative;
}
.first,.second,.third {
position: absolute;
width: 100px;
line-height: 100px;
text-align: center;
}
.first {
background: lightblue;
position: absolute;
z-index: 10;
}
.second {
background: lightcoral;
position: absolute;
left: 200px;
}
.third {
background: lawngreen;
position: absolute;
left: 100px;
}
Could anyone please tell if there is anything wrong with the css I've tried or any other method in order to achieve this.
Upvotes: 1
Views: 3741
Reputation: 194
you should use event.stopPropagation()
<div className="second" onClick={(event) =>
event.stopPropagation()
console.log("second div")
}>
second
</div>
Upvotes: 3