Let's say I have a responsive ReactJS component (Outer
) that does something when I click it. Inside the larger component I want a single button that does something special when I double-click it.
export default function FancyDoubleClickHandler() {
function handleOuterClick() {
console.log("outer single click")
}
function handleInnerClick() {
???
}
return (
<div id="outer" onClick={handleOuterClick}>
<p>Click on me to do outer click</p>
<button id="inner" onDoubleClick={handleInnerClick}>
<p>
Click on me to do outer click -- OR --
Double-click on me to do special inner click thing only
</p>
</button>
</div>
)
}
As written, the onDoubleClick
event does not prevent the outer onClick
event from firing (twice). That basic problem is solved in this SO question, by avoiding onDoubleClick
and instead using a unified click handler that fires single clicks only after a timeout has expired:
function handleAllClicks(event) {
clearTimeout(timer);
if (event.detail === 1) {
timer = setTimeout(() => {
console.log("SINGLE CLICK");
}, SOME_DOUBLECLICK_DELAY)
} else if (event.detail === 2) {
console.log("DOUBLE CLICK");
}
}
But in that answer, there's no need to stop event propagation, so a double click on the inner button still propagates two click events to handleOuterClick
. In my case, I need to suppress those outer events in the case of a double-click.
In (modern) ReactJS, how can I achieve an architecture in which an inner element intercepts and handles a double-click, but propagates a single click upward?