Skip to content

useSwiping

You can handle the user swipe actions using this hook, and it can also handle the mouse swipes.

Parameters

  1. the swipe action handler function that takes the SwipeAction object as a parameter.
  2. the swipe options:
NameTypeDescription
refRefObjectthe container element reference (default is window).

Return Values

a ref object of the target element.

SwipeAction Object

NameTypeDescription
typeStringthe swipe type which can be start, end, or moving.
deltaXNumberthe swipe distance x from the initialX value.
deltaYNumberthe swipe distance y from the initialY value.
initialXNumberthe initial x position.
initialYNumberthe initial y position.
eventEventthe TouchEvent or MouseEvent if you are using the mouse property.

Example Usage

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

let start = 0;

export default function Slider() {
  const ref = useSwiping(action => {
    if (action.type === 'start') start = window.scrollY;

    window.scrollTo({ top: start + action.deltaY });
  });

  return (
    <div ref={ref}>
      <p>Swipe to the left!</p>
      <ul>
        {new Array(10).fill(null).map((_, i) => (
          <li key={i}>{i}</li>
        ))}
      </ul>
    </div>
  );
}
import { useSwiping } from 'react-pre-hooks';

let start = 0;

export default function Slider() {
  const ref = useSwiping(action => {
    if (action.type === 'start') start = window.scrollY;

    window.scrollTo({ top: start + action.deltaY });
  });

  return (
    <div ref={ref}>
      <p>Swipe to the left!</p>
      <ul>
        {new Array(10).fill(null).map((_, i) => (
          <li key={i}>{i}</li>
        ))}
      </ul>
    </div>
  );
}

Released under the MIT License.