Skip to content

usePointers

Handle all the pointer events at once using this hook.

Parameters

  1. a function that handles the pointer events that takes two arguments, the PointerEvent object and a pointer event list.
  2. and some options:
NameTypeDescription
refRefObjectthe target element reference.
captureBooleanthe pointer will be targeted at the capture element until capture is released or removed from the pointers list.

Return Values

a ref object of the target element.

TIP

Some browsers has a built-in touch actions, so if you try to use it the browsers will cancel it, you can disable these defaut touch actions using CSS:

css
...
touch-action: none;
...
...
touch-action: none;
...

Example Usage

tsx
import { usePointers } from 'react-pre-hooks';

export default function Example() {
  const ref = usePointers((event, list) => {
    let pointer = document.getElementById(event.pointerId + '');

    if (!pointer) {
      pointer = document.createElement('div');
      pointer.id = event.pointerId + '';
      pointer.classList.add('pointer');
    }

    pointer.style.top = event.clientY + 'px';
    pointer.style.left = event.clientX + 'px';

    if (event.type === 'pointerdown') {
      document.body.appendChild(pointer);
    } else if (!list.find(e => e.pointerId === event.pointerId)) {
      pointer.remove();
    }
  });

  return (
    <div ref={ref}>
      <p>Start pointing with your fingers!</p>
    </div>
  );
}
import { usePointers } from 'react-pre-hooks';

export default function Example() {
  const ref = usePointers((event, list) => {
    let pointer = document.getElementById(event.pointerId + '');

    if (!pointer) {
      pointer = document.createElement('div');
      pointer.id = event.pointerId + '';
      pointer.classList.add('pointer');
    }

    pointer.style.top = event.clientY + 'px';
    pointer.style.left = event.clientX + 'px';

    if (event.type === 'pointerdown') {
      document.body.appendChild(pointer);
    } else if (!list.find(e => e.pointerId === event.pointerId)) {
      pointer.remove();
    }
  });

  return (
    <div ref={ref}>
      <p>Start pointing with your fingers!</p>
    </div>
  );
}

Released under the MIT License.