I have a simple react component defined as such:
export function ClickableContainer({onClick, children}) {
return <div onClick={(event) => {
onClick(event);
}>{ children }</div>
}
Sometimes I might want to have clickable things inside this component:
export function Page() {
return <ClickableContainer onClick={() => alert("stop poking me")}>
<button onClick={() => alert("me like that")}>Please Click</button>
</ClickableContainer>
}
I want to find a way to modify ClickableContainer
such that clicks on its children don’t also register as clicks on the parent element.
Let me make it clear, I am aware I could do:
export function Page() {
return <ClickableContainer onClick={() => alert("stop poking me")}>
<button onClick={(event) => {
event.stopPropagation();
alert("me like that");
}}>Please Click</button>
</ClickableContainer>
}
But I DO NOT want to do this. I would rather save the users of my component the cognitive load and handle it inside the parent.
I have tried:
export function ClickableContainer({onClick, children}) {
return <div onClick={(event) => {
if (event.eventPhase !== 3) onClick(event);
}>{ children }</div>
}
and
export function ClickableContainer({onClick, children}) {
return <div onClick={(event) => {
if (event.currentTarget == event.target) onClick(event);
}>{ children }</div>
}
But these prevent clicks from registering altogteher.
It doesn’t have to be simple or pretty, is there any way to tell if an event has already been handled by a child component?