I have an App
component and a Box
component, which is a child of the App
. I want to listen to click on the App
component,t and if a Box
was clicked, I don't want that event to propagate.
This is the code I have written:
App.js:
function App() {
const handleClick=()=>{
console.log("Clicked on the app")
}
document.addEventListener('click', handleClick, true);
return (
<div className="wrapper">
<Box ></Box>
</div>
);
}
export default App;
Box.js:
export function Box(){
const onSelect=(e)=>{
e.stopPropagation();
}
return (
<div tabIndex="0" onClick={onSelect}>Box</div>
)
}
However, I observe two things:
- Every click produces two console statements instead of one
- Click on Box does not stop propagation and the console statements are still printed twice
Why is this happening and how do I get around it?