@artcom/react-tap-tolerance
v0.2.0
Published
React hook that keeps taps clicking on imprecise touch hardware by tolerating small pointer movement.
Readme
@artcom/react-tap-tolerance
A React hook that keeps taps clicking on imprecise touch hardware - IR touch
frames, touch foils and similar - where the reported position jitters while
a finger rests on the screen. Browsers treat such a press as a tiny drag and
drop its click, so buttons feel unresponsive. This hook fills in the
missing clicks.
Installation
npm install @artcom/react-tap-toleranceUsage
Call the hook once near the root of your app. Every onClick in the app
benefits; no per-component changes are needed.
import { useTapTolerance } from "@artcom/react-tap-tolerance"
function App() {
useTapTolerance()
return <YourApp />
}useTapTolerance(options?)
| Option | Type | Default | Description |
| ----------------- | --------- | ------- | ----------------------------------------------------------------------------- |
| threshold | number | 100 | Max distance in CSS pixels a pointer may travel from its start and still tap. |
| scrollThreshold | number | 30 | Max distance for a press the browser turned into a scroll (see below). |
| pinchZoom | boolean | false | Allow two-finger pinch-zoom on the page. |
How it works
For every pointer (touch, pen or mouse) the hook remembers where it went down and on which element.
- If the pointer ever moves further than
threshold, the press is a drag and never produces a click from the hook - even if it comes back. - On release, the hook waits a frame. If the browser delivered its own click
for the press, nothing happens. Otherwise the hook dispatches a
clickon the element the press started on. - If the browser clicks a common ancestor instead (because the pointer drifted onto a neighbouring element), that click is replaced by one on the pressed element. It still bubbles through the ancestor.
- Presses on disabled or removed elements never click.
Each tap therefore produces exactly one click. Clicks the browser delivers correctly, and keyboard clicks, are left untouched.
Scroll areas
Inside scrollable elements (overflow: auto/scroll) the browser may turn
a jittering press into a scroll and cancel the pointer, so it never clicks.
The hook keeps following the finger through touch events: if it lifts within
scrollThreshold, the pressed element is still clicked. The list may move a
few pixels before the click; longer swipes scroll without clicking.
Multi-finger gestures, such as a pinch, never click.
touch-action
While mounted, the hook sets touch-action: none on document.body (or
pinch-zoom with pinchZoom: true), so jitter doesn't pan the page or
trigger browser gestures. Scrolling the page itself is disabled; scroll
areas inside the page keep scrolling. The previous value is restored on
unmount.
Pinch-zoom is off by default: in a kiosk, a visitor who zooms in leaves the next visitor with no way back.
Development
npm install
npm test
npm run lint
npm run build