Handle mouse down/up and click events once with React Hooks
The issue
Sometimes you need to make a button
clickable with click and mouse down or mouse up actions.
The first solution that comes to mind would be to add only one event listener onMouseDown
/onMouseUp
but without an onClick
event listener the element is not accessible anymore. It's now hard to click for people with disabilities or with keyboard navigation.
If we set both onMouseDown
/onMouseUp
and onClick
event listeners, the common click handler function would be called twice with a mouse. So we have
We need to handle either one event or the other but not both, knowing that it can happen that only one of them is activated.
Improvement
This piece of code is subject to improvement, it needs to:
- Handle touch devices events
onTouchStart
andonTouchEnd
. - Transcribe it in a hooks library. Done: github.com/dimitrinicolas/use-mouse-action