useClick()
npm i @react-hook/click
A React hook for conditionally firing a function when an element is clicked - for instance if you only want a click even to fire on double-clicks.
Quick Start
import useClick from '@react-hook/click'
const Component = (props) => {
// this onClick even will only fire if this was a double-click
const maybeHandleClick = useClick('double', console.log)
return <button onClick={maybeHandleClick}>Double-click me</button>
}
API
useClick(conditions, onClick)
-
conditions
string | string[]
- One or several conditions about the click that must be met in order
for the
onClick
callback to fire -
Options
-
single
- Checks for
e.detail === 1
- Checks for
-
double
- Checks for
e.detail === 2
- Checks for
-
triple
- Checks for
e.detail === 3
- Checks for
-
left
- Checks for
e.button === 0
- Checks for
-
middle
- Checks for
e.button === 1
- Checks for
-
right
- Checks for
e.button === 2
- Checks for
-
shift
- Checks for
e.shiftKey === true
- Checks for
-
control
- Checks for
e.ctrlKey === true
- Checks for
-
meta
- Checks for
e.metaKey === true
- Checks for
-
alt
- Checks for
e.altKey === true
- Checks for
-
-
Complex queries
-
detail=1
- Equality check, i.e.
event.detail === 1
- Equality check, i.e.
-
shiftKey
- Boolean check, i.e.
event.shiftKey === true
- Boolean check, i.e.
-
shiftKey+metaKey
-
AND
, i.e.event.shiftKey === true && event.metaKey === true
-
-
shiftKey|metaKey+detail=1
-
OR
, i.e.event.shiftKey === true || event.metaKey === true && detail === 1
-
-
-
onClick
<function>
- A callback that fires when all of the
conditions
are met. The callback signature is:onClick(event, data: {x, y, count})
-
event
- The React synthetic event
-
data
<object>
-
x
<int>
- The number of pixels from the left edge of the event target where the click occurred
-
y
<int>
- The number of pixels from the top edge of the event target where the click occurred
-
count
<int>
- The number of times the event target was clicked in succession
-
onClick
handler
Returns an (e: React.MouseEvent<HTMLElement>) => void
LICENSE
MIT