### Install and Run Examples Locally Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Install dependencies and start the local development server to test changes in examples. Ensure Node 16 and Yarn v1 are used for initial setup. ```sh yarn install yarn start:examples:local ``` -------------------------------- ### Setup and Run Documentation Locally Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Navigate to the docs directory, install its dependencies, and start the local documentation server. Requires Node 18+. ```sh cd docs yarn install yarn start ``` -------------------------------- ### Build Examples Locally Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Execute this command from the project root to build the examples. After building, navigate to the `examples` directory and start a local HTTP server to validate the examples. ```sh yarn examples:build ``` -------------------------------- ### Serve Examples Locally Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md After building the examples, change the directory to `examples` and run this command to start a Python 3 HTTP server on port 8080. Access the examples at `http://localhost:8080/`. ```sh cd examples python -m http.server 8080 ``` -------------------------------- ### Build and Deploy Examples to GitHub Pages Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Run this command from the project root to build and publish the examples application to GitHub Pages. Ensure you have updated the version in `examples/package.json` and run `yarn` beforehand. ```sh yarn examples:build:publish ``` -------------------------------- ### Start Local Development Server Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/README.md Starts a local development server for live preview. Changes are reflected without server restart. ```bash $ yarn start ``` -------------------------------- ### Install Dependencies Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/README.md Run this command to install project dependencies using Yarn. ```bash $ yarn ``` -------------------------------- ### Basic Swipe Handler Setup with useSwipeable Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/introduction.mdx Import the `useSwipeable` hook and configure basic swipe event handlers. Spread the returned handlers onto any HTML element to enable swipe detection. ```jsx import { useSwipeable } from 'react-swipeable'; const handlers = useSwipeable({ onSwiped: (eventData) => console.log("User Swiped!", eventData), ...config, }); return
You can swipe here
; ``` -------------------------------- ### Carousel Logic: Position, Pattern, and Initial State Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-pattern.mdx Sets up the `getOrder` function for item positioning, defines the swipe pattern, and initializes the carousel's starting state. ```typescript const getOrder = (index: number, pos: number, numItems: number) => { return index - pos < 0 ? numItems - Math.abs(index - pos) : index - pos; }; const pattern = [UP, DOWN, UP, DOWN]; const getInitialState = (numItems: number): CarouselState => ({ pos: numItems - 1, sliding: false, dir: NEXT }); ``` -------------------------------- ### React Carousel with Swipeable Pattern Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-pattern.mdx This component implements a carousel that advances slides based on a specific swipe pattern. It uses `useSwipeable` to handle swipe events and `React.useReducer` for state management. Ensure `react-swipeable` is installed and imported. ```typescript const Carousel: FunctionComponent<{children: ReactNode}> = (props) => { const numItems = React.Children.count(props.children); const [state, dispatch] = React.useReducer(reducer, getInitialState(numItems)); const slide = (dir: Direction) => { dispatch({ type: dir, numItems }); setTimeout(() => { dispatch({ type: 'stopSliding' }); }, 50); }; const [pIdx, setPIdx] = React.useState(0); const handleSwiped = (eventData: SwipeEventData) => { if (eventData.dir === pattern[pIdx]) { // user successfully got to the end of the pattern! if (pIdx + 1 === pattern.length) { setPIdx(pattern.length); slide(NEXT); setTimeout(() => { setPIdx(0); }, 50); } else { // user is cont. with the pattern setPIdx((i) => (i += 1)); } } else { // user got the next pattern step wrong, reset pattern setPIdx(0); } }; const handlers = useSwipeable({ onSwiped: handleSwiped, onTouchStartOrOnMouseDown: (({ event }) => event.preventDefault()), touchEventOptions: { passive: false }, preventScrollOnSwipe: true, trackMouse: true }); return ( <> Swipe the pattern below, within this box, to make the carousel go to the next slide {`\n`}

Swipe: 0} /> 1} /> 2} /> 3} />

{React.Children.map(props.children, (child, index) => ( {child} ))}
); }; ``` -------------------------------- ### Accessing Swipe Event Data with `SwipeEventData` Source: https://context7.com/formidablelabs/react-swipeable/llms.txt The `SwipeEventData` object provides detailed information about the swipe gesture, including start position, displacement, velocity, and direction. This data is available in all swipe-related callbacks. ```tsx import { useSwipeable, SwipeEventData, SwipeDirections } from 'react-swipeable'; function VelocityTracker() { const handlers = useSwipeable({ onSwiped: (data: SwipeEventData) => { const { event, initial, first, deltaX, deltaY, absX, absY, velocity, vxvy, dir, } = data; console.log(`Swiped ${dir}: ${absX}px horizontal, ${absY}px vertical`); console.log(`Speed: ${velocity.toFixed(3)} px/ms`); console.log(`Started at [${initial[0]}, ${initial[1]}]`); }, }); return
Swipe here
; } ``` -------------------------------- ### Build Static Site Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/README.md Generates the static content for the website into the 'build' directory. ```bash $ yarn build ``` -------------------------------- ### Import necessary hooks and types Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-pattern.mdx Import `useSwipeable` hook, directions, and `SwipeEventData` from the library. Local UI components are also imported. ```typescript import React, { FunctionComponent, ReactNode } from 'react'; import { useSwipeable, UP, DOWN, SwipeEventData } from 'react-swipeable'; import { Wrapper, CarouselContainer, CarouselSlot, PatternBox, PREV, NEXT, D } from '../components'; ``` -------------------------------- ### Run All Tests Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Execute all project tests, including unit tests, linting, prettier checks, and build processes, using a single command. ```sh yarn test ``` -------------------------------- ### Add a Changeset Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Create a changeset file to record changes for package versioning and publishing. This command initiates an interactive process to select packages and specify version bumps and summary messages. ```sh yarn changeset ``` -------------------------------- ### Run Unit Tests Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Execute all unit tests using Jest and React Testing Library. Use the watch mode to automatically re-run tests on file changes. ```sh yarn run test:unit ``` ```sh yarn run test:unit:watch ``` -------------------------------- ### Configuration Props Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md These props allow customization of the swipe detection behavior, including minimum distance, duration, and input tracking. ```APIDOC ## Configuration Props ### Description Customize swipe detection behavior. ### Props - `delta` (number | object): Minimum distance (px) before a swipe starts. Defaults to `10`. Can be an object like `{ up: 20, down: 20 }` to specify different deltas per direction. - `preventScrollOnSwipe` (boolean): Prevents page scrolling during a swipe. Defaults to `false`. - `trackTouch` (boolean): Enables tracking of touch input. Defaults to `true`. - `trackMouse` (boolean): Enables tracking of mouse input. Defaults to `false`. - `rotationAngle` (number): Sets a rotation angle. Defaults to `0`. - `swipeDuration` (number): Maximum allowable duration of a swipe in milliseconds. Swipes longer than this will not be considered swipes. Defaults to `Infinity`. A sensible value could be `250`. - `touchEventOptions` (object): Options for touch event listeners, e.g., `{ passive: true }`. Defaults to `{ passive: true }`. `preventScrollOnSwipe` supersedes `touchEventOptions.passive` for `touchmove`. ``` -------------------------------- ### Lint and Format Code Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Run ESLint for code linting and Prettier for code formatting. The build will fail if linting or formatting rules are violated. Use 'yarn run format' to fix Prettier errors. ```sh yarn run lint ``` ```sh yarn run prettier ``` ```sh yarn run format ``` -------------------------------- ### Enable Mouse Drag Support with `trackMouse` Source: https://context7.com/formidablelabs/react-swipeable/llms.txt Setting `trackMouse: true` enables `onMouseDown` and attaches `mousemove`/`mouseup` listeners to the document, allowing desktop drag gestures to trigger the same callbacks as touch swipes. ```tsx import { useSwipeable } from 'react-swipeable'; function DesktopAndMobile() { const handlers = useSwipeable({ onSwipedLeft: () => console.log('left (touch or mouse drag)'), onSwipedRight: () => console.log('right (touch or mouse drag)'), trackMouse: true, // enables mouse-drag detection trackTouch: true, // still track touch (default) swipeDuration: 500, }); return (
Drag me on desktop or swipe on mobile
); } ``` -------------------------------- ### Manual Publish to npm Source: https://github.com/formidablelabs/react-swipeable/blob/main/CONTRIBUTING.md Manually publish a new version of the package to npm. This involves updating the version, publishing, and pushing tags to Git. ```sh npm version [patch|minor|major|] npm publish git push --follow-tags ``` -------------------------------- ### Basic Swipeable Component with `useSwipeable` Hook Source: https://context7.com/formidablelabs/react-swipeable/llms.txt Implement swipe and touch gesture handling by spreading the returned handlers onto a target DOM element. Configure callbacks for directional swipes, lifecycle events, and raw pointer events. Customize behavior with options like `delta`, `preventScrollOnSwipe`, and `trackMouse`. ```tsx import { useSwipeable, SwipeEventData } from 'react-swipeable'; function SwipeZone() { const handlers = useSwipeable({ // --- Direction callbacks --- onSwipedLeft: (data: SwipeEventData) => console.log('← swiped left', data.absX, 'px'), onSwipedRight: (data: SwipeEventData) => console.log('→ swiped right', data.absX, 'px'), onSwipedUp: (data: SwipeEventData) => console.log('↑ swiped up', data.absY, 'px'), onSwipedDown: (data: SwipeEventData) => console.log('↓ swiped down', data.absY, 'px'), // --- Lifecycle callbacks --- onSwipeStart: (data) => console.log('swipe started, first =', data.first), // first is always true here onSwiping: (data) => console.log('swiping…', data.dir, data.velocity), onSwiped: (data) => console.log('swipe ended', data.deltaX, data.deltaY), onTap: ({ event }) => console.log('tapped', event), // --- Pass-through raw event callbacks --- onTouchStartOrOnMouseDown: ({ event }) => console.log('pointer down', event), onTouchEndOrOnMouseUp: ({ event }) => console.log('pointer up', event), // --- Configuration --- delta: 10, // px before a swipe is registered (default: 10) preventScrollOnSwipe: true, // call e.preventDefault() on touchmove (default: false) trackTouch: true, // track touch input (default: true) trackMouse: true, // also track mouse drag (default: false) rotationAngle: 0, // rotate coordinate system by N degrees (default: 0) swipeDuration: 500, // ms; swipes longer than this are ignored (default: Infinity) touchEventOptions: { passive: false },// listener options for touchstart/touchmove/touchend }); return (
Swipe or drag me in any direction
); } ``` -------------------------------- ### Configurable Delta for Swipe Directions Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md Specify different minimum swipe distances (in pixels) for each direction (up, down, left, right). Directions not specified will default to 10px. ```javascript { delta: { up: 20, down: 20 } // up and down ">= 20", left and right default to ">= 10" } ``` -------------------------------- ### Configure Per-Direction Minimum Swipe Distance with `delta` Source: https://context7.com/formidablelabs/react-swipeable/llms.txt Use `delta` to set a minimum distance for swipes in specific directions. Directions not specified fall back to a default of 10px. This allows for fine-grained control over gesture sensitivity. ```tsx import { useSwipeable } from 'react-swipeable'; function DirectionalDelta() { const handlers = useSwipeable({ onSwipedLeft: () => console.log('left — needs 30 px'), onSwipedRight: () => console.log('right — needs 30 px'), onSwipedUp: () => console.log('up — needs 5 px (very sensitive)'), onSwipedDown: () => console.log('down — defaults to 10 px'), // Object form: keys are lowercase direction names delta: { left: 30, right: 30, up: 5 }, // 'down' defaults to 10 }); return
Swipe
; } ``` -------------------------------- ### Attach useSwipeable to Document Source: https://context7.com/formidablelabs/react-swipeable/llms.txt To detect swipes on the entire document, extract the ref callback from useSwipeable and call it manually with the document object. Ensure cleanup by calling ref with an empty object on unmount. ```tsx import React, { useEffect } from 'react'; import { useSwipeable } from 'react-swipeable'; function DocumentSwipe() { const { ref } = useSwipeable({ onSwipedLeft: () => console.log('doc swipe left'), onSwipedRight: () => console.log('doc swipe right'), }) as { ref: React.RefCallback }; useEffect(() => { ref(document); // attach listeners to document return () => ref({} as any); // cleanup on unmount }); return

Swipe anywhere on the page

; } ``` -------------------------------- ### Configuration Props and Default Values for React Swipeable Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md Configure swipe behavior such as minimum distance, scroll prevention, input tracking, and swipe duration. Defaults are provided for convenience. ```javascript { delta: 10, // min distance(px) before a swipe starts. *See Notes* preventScrollOnSwipe: false, // prevents scroll during swipe (*See Details*) trackTouch: true, // track touch input trackMouse: false, // track mouse input rotationAngle: 0, // set a rotation angle swipeDuration: Infinity, // allowable duration of a swipe (ms). *See Notes* touchEventOptions: { passive: true }, // options for touch listeners (*See Details*) } ``` -------------------------------- ### useSwipeable Hook Source: https://context7.com/formidablelabs/react-swipeable/llms.txt The `useSwipeable` hook is the primary API for handling swipe and touch gestures. It accepts an options object for configuration and callbacks, and returns handlers that should be spread onto the target DOM element. ```APIDOC ## `useSwipeable(options)` — Core Hook The only public API of the library. Accepts a configuration/callback object and returns `handlers` (containing `ref` and optionally `onMouseDown`) that must be spread onto the target element. The hook uses refs internally to avoid re-renders on every pointer move event. ### Parameters #### Options Object - **`onSwipedLeft`** (function) - Callback for swipe left. - **`onSwipedRight`** (function) - Callback for swipe right. - **`onSwipedUp`** (function) - Callback for swipe up. - **`onSwipedDown`** (function) - Callback for swipe down. - **`onSwipeStart`** (function) - Callback when a swipe gesture begins. - **`onSwiping`** (function) - Callback during a swipe gesture. - **`onSwiped`** (function) - Callback when a swipe gesture ends. - **`onTap`** (function) - Callback for tap events. - **`onTouchStartOrOnMouseDown`** (function) - Callback for pointer down events (touch or mouse). - **`onTouchEndOrOnMouseUp`** (function) - Callback for pointer up events (touch or mouse). - **`delta`** (number) - Minimum pixels before a swipe is registered (default: 10). - **`preventScrollOnSwipe`** (boolean) - Call `e.preventDefault()` on touchmove (default: false). - **`trackTouch`** (boolean) - Track touch input (default: true). - **`trackMouse`** (boolean) - Track mouse drag (default: false). - **`rotationAngle`** (number) - Rotate coordinate system by N degrees (default: 0). - **`swipeDuration`** (number) - Maximum milliseconds for a swipe gesture to be considered valid (default: Infinity). - **`touchEventOptions`** (object) - Listener options for touchstart/touchmove/touchend. ### Returns - **`handlers`** (object) - An object containing `ref` and optionally `onMouseDown` that must be spread onto the target element. ### Example ```tsx import { useSwipeable, SwipeEventData } from 'react-swipeable'; function SwipeZone() { const handlers = useSwipeable({ onSwipedLeft: (data: SwipeEventData) => console.log('← swiped left', data.absX, 'px'), onSwipedRight: (data: SwipeEventData) => console.log('→ swiped right', data.absX, 'px'), onSwipedUp: (data: SwipeEventData) => console.log('↑ swiped up', data.absY, 'px'), onSwipedDown: (data: SwipeEventData) => console.log('↓ swiped down', data.absY, 'px'), delta: 10, preventScrollOnSwipe: true, trackMouse: true, }); return (
Swipe or drag me in any direction
); } ``` ``` -------------------------------- ### Use `touch-action` CSS for Scroll Prevention Source: https://context7.com/formidablelabs/react-swipeable/llms.txt For optimal performance, use the CSS `touch-action` property instead of `preventScrollOnSwipe` to offload scroll prevention to the browser compositor. This keeps all listeners passive. ```tsx import { useSwipeable } from 'react-swipeable'; // Static: always prevent vertical scroll in the swipeable zone function StaticTouchAction() { const handlers = useSwipeable({ onSwiped: (data) => console.log('swiped', data.dir), }); return (
{/* pan-y = allow vertical scroll, block horizontal = horizontal swipes always captured */} Swipe horizontally
); } ``` ```tsx // Dynamic: toggle scroll lock based on swipe state function DynamicTouchAction() { const [isScrollLocked, setScrollLocked] = React.useState(false); const handlers = useSwipeable({ onSwipeStart: () => setScrollLocked(true), onSwiped: () => setScrollLocked(false), }); return (
Swipe to lock scroll
); } ``` -------------------------------- ### Implement Gesture Pattern Lock with onSwiped Source: https://context7.com/formidablelabs/react-swipeable/llms.txt Use the `onSwiped` event to track swipe directions and implement a sequence-based unlock. Ensure `preventScrollOnSwipe` is true and `trackMouse` is enabled for desktop support. The `onTouchStartOrOnMouseDown` handler prevents default behavior to avoid conflicts. ```tsx import React, { useState } from 'react'; import { useSwipeable, UP, DOWN, SwipeEventData } from 'react-swipeable'; const SECRET_PATTERN = [UP, DOWN, UP, DOWN]; // Konami-style pattern function PatternLock() { const [step, setStep] = useState(0); const [unlocked, setUnlocked] = useState(false); const handleSwiped = (data: SwipeEventData) => { if (data.dir === SECRET_PATTERN[step]) { if (step + 1 === SECRET_PATTERN.length) { setUnlocked(true); setTimeout(() => { setUnlocked(false); setStep(0); }, 1500); } else { setStep((s) => s + 1); } } else { setStep(0); // wrong direction — reset } }; const handlers = useSwipeable({ onSwiped: handleSwiped, onTouchStartOrOnMouseDown: ({ event }) => event.preventDefault(), touchEventOptions: { passive: false }, preventScrollOnSwipe: true, trackMouse: true, }); return (
{unlocked ? '🔓 Unlocked!' : `Step ${step + 1} / ${SECRET_PATTERN.length}: swipe ${SECRET_PATTERN[step]}`}

Pattern: ↑ ↓ ↑ ↓

); } ``` -------------------------------- ### Share Ref from useSwipeable Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/faq.md To use the ref provided by `useSwipeable` along with your own ref, create a custom ref passthrough function. This function calls the `useSwipeable` ref prop and then sets your own ref's current value. ```javascript const MyComponent = () => { const handlers = useSwipeable({ onSwiped: () => console.log('swiped') }) // setup ref for your usage const myRef = React.useRef(); const refPassthrough = (el) => { // call useSwipeable ref prop with el handlers.ref(el); // set myRef el so you can access it yourself myRef.current = el; } return (
} ``` -------------------------------- ### Add Swipe Listener to Document Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/faq.md Use `useSwipeable` with a `RefCallback` to attach swipe listeners directly to the `document`. Remember to clean up listeners by calling the ref with an empty object in the `useEffect` cleanup function to prevent memory leaks and potential issues. ```javascript const { ref } = useSwipeable({ ... }) as { ref: RefCallback }; useEffect(() => { ref(document); // Clean up swipeable event listeners return () => ref({}); }); ``` -------------------------------- ### Carousel Imports Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-carousel.mdx Imports necessary hooks and UI components for the carousel implementation. ```typescript import { useSwipeable } from 'react-swipeable'; import { Wrapper, CarouselContainer, CarouselSlot, SlideButtonContainer, SlideButton, PREV, NEXT } from '../components'; ``` -------------------------------- ### Event Handler Props Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md These props are callback functions that are triggered by various swipe and tap events. Each handler receives `SwipeEventData` or specific event objects as arguments. ```APIDOC ## Event Handler Props ### Description Callback functions triggered by swipe and tap events. ### Props - `onSwiped` (SwipeEventData) => void: Called after any swipe. - `onSwipedLeft` (SwipeEventData) => void: Called after a LEFT swipe. - `onSwipedRight` (SwipeEventData) => void: Called after a RIGHT swipe. - `onSwipedUp` (SwipeEventData) => void: Called after an UP swipe. - `onSwipedDown` (SwipeEventData) => void: Called after a DOWN swipe. - `onSwipeStart` (SwipeEventData) => void: Called at the start of a swipe. The `first` property of `SwipeEventData` will be `true`. - `onSwiping` (SwipeEventData) => void: Called during a swipe. - `onTap` ({ event }) => void: Called after a tap. - `onTouchStartOrOnMouseDown` ({ event }) => void: Called for `touchstart` and `mousedown` events. - `onTouchEndOrOnMouseUp` ({ event }) => void: Called for `touchend` and `mouseup` events. ``` -------------------------------- ### Share DOM Ref with useSwipeable Source: https://context7.com/formidablelabs/react-swipeable/llms.txt To access the DOM element alongside useSwipeable, create a passthrough ref function that calls both the library's ref and your own. ```tsx import React from 'react'; import { useSwipeable } from 'react-swipeable'; function SharedRef() { const myRef = React.useRef(null); const handlers = useSwipeable({ onSwiped: () => console.log('element rect:', myRef.current?.getBoundingClientRect()), }); // Merge useSwipeable's ref with your own const refPassthrough = (el: HTMLDivElement | null) => { handlers.ref(el); // attach swipeable listeners myRef.current = el; // keep your own reference }; return
Swipe me
; } ``` -------------------------------- ### Touch Event Listener Options Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md Customize options for touch event listeners, such as `passive: true`. Note that `preventScrollOnSwipe` can override the `passive` option for `touchmove` events. ```javascript { touchEventOptions: { passive: true }, // options for touch listeners (*See Details*) } ``` -------------------------------- ### Carousel Component Implementation Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-carousel.mdx The main Carousel component that integrates the useSwipeable hook, manages state with useReducer, and renders carousel items with navigation buttons. ```typescript const Carousel: FunctionComponent<{children: ReactNode}> = (props) => { const numItems = React.Children.count(props.children); const [state, dispatch] = React.useReducer(reducer, getInitialState(numItems)); const slide = (dir: Direction) => { dispatch({ type: dir, numItems }); setTimeout(() => { dispatch({ type: 'stopSliding' }); }, 50); }; const handlers = useSwipeable({ onSwipedLeft: () => slide(NEXT), onSwipedRight: () => slide(PREV), swipeDuration: 500, preventScrollOnSwipe: true, trackMouse: true }); return (
{React.Children.map(props.children, (child, index) => ( {child} ))} slide(PREV)} float="left"> Prev slide(NEXT)} float="right"> Next
); }; ``` -------------------------------- ### Image Carousel with useSwipeable Source: https://context7.com/formidablelabs/react-swipeable/llms.txt A complete swipeable carousel integrating useReducer for state management. It utilizes directional swipe callbacks, swipeDuration, preventScrollOnSwipe, and trackMouse for a rich user experience. ```tsx import React, { FunctionComponent, ReactNode, useReducer } from 'react'; import { useSwipeable } from 'react-swipeable'; const PREV = 'PREV'; const NEXT = 'NEXT'; type Direction = typeof PREV | typeof NEXT; interface State { pos: number; sliding: boolean; dir: Direction; } type Action = { type: Direction; numItems: number } | { type: 'stopSliding' }; const getOrder = (i: number, pos: number, n: number) => i - pos < 0 ? n - Math.abs(i - pos) : i - pos; function reducer(state: State, action: Action): State { switch (action.type) { case PREV: return { dir: PREV, sliding: true, pos: state.pos === 0 ? action.numItems - 1 : state.pos - 1 }; case NEXT: return { dir: NEXT, sliding: true, pos: state.pos === action.numItems - 1 ? 0 : state.pos + 1 }; case 'stopSliding': return { ...state, sliding: false }; default: return state; } } const Carousel: FunctionComponent<{ children: ReactNode }> = ({ children }) => { const numItems = React.Children.count(children); const [state, dispatch] = useReducer(reducer, { pos: numItems - 1, sliding: false, dir: NEXT }); const slide = (dir: Direction) => { dispatch({ type: dir, numItems }); setTimeout(() => dispatch({ type: 'stopSliding' }), 50); }; const handlers = useSwipeable({ onSwipedLeft: () => slide(NEXT), onSwipedRight: () => slide(PREV), swipeDuration: 500, // ignore drags longer than 500 ms preventScrollOnSwipe: true, // block page scroll while swiping trackMouse: true, // also works with mouse drag on desktop }); return (
{React.Children.map(children, (child, i) => (
{child}
))}
); }; // Usage: // // Slide 1 // Slide 2 // Slide 3 // ``` -------------------------------- ### Static Swipeable Component in React Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/examples.md Use this for basic swipe gesture handling where configuration is static. Ensure touch-action is set to 'pan-y' for vertical scrolling. ```jsx const handlers = useSwipeable({ onSwiped: (eventData) => console.log("User Swiped!", eventData), ...config, }); return
Swipe here
; ``` -------------------------------- ### Carousel State and Reducer Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-carousel.mdx Defines types, interfaces, and a reducer function for managing the carousel's state, including position, sliding status, and direction. ```typescript type Direction = typeof PREV | typeof NEXT; interface CarouselState { pos: number; sliding: boolean; dir: Direction; } type CarouselAction = | { type: Direction, numItems: number } | { type: 'stopSliding' }; const getOrder = (index: number, pos: number, numItems: number) => { return index - pos < 0 ? numItems - Math.abs(index - pos) : index - pos; }; const getInitialState = (numItems: number): CarouselState => ({ pos: numItems - 1, sliding: false, dir: NEXT }); function reducer(state: CarouselState, action: CarouselAction): CarouselState { switch (action.type) { case PREV: return { ...state, dir: PREV, sliding: true, pos: state.pos === 0 ? action.numItems - 1 : state.pos - 1 }; case NEXT: return { ...state, dir: NEXT, sliding: true, pos: state.pos === action.numItems - 1 ? 0 : state.pos + 1 }; case 'stopSliding': return { ...state, sliding: false }; default: return state; } } ``` -------------------------------- ### Setting Swipe Duration Limit Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md Limit the maximum duration (in milliseconds) for a swipe to be recognized. Swipes exceeding this duration will not trigger callbacks and stop being tracked. ```javascript { swipeDuration: 250 // only swipes under 250ms will trigger callbacks } ``` -------------------------------- ### SwipeEventData Structure Source: https://context7.com/formidablelabs/react-swipeable/llms.txt The `SwipeEventData` object is passed to all swipe-related callbacks and contains detailed information about the gesture. ```APIDOC ## `SwipeEventData` — Event Payload All swipe callbacks (`onSwiped`, `onSwiping`, `onSwipeStart`, `onSwipedLeft`, etc.) receive a `SwipeEventData` object with full motion details. ### Fields - **`event`** (TouchEvent | MouseEvent) - The original DOM event. - **`initial`** ([number, number]) - The [x, y] coordinates where the swipe started. - **`first`** (boolean) - True only for the very first move event of this swipe. - **`deltaX`** (number) - Current X position minus initial X position (signed). - **`deltaY`** (number) - Current Y position minus initial Y position (signed). - **`absX`** (number) - The absolute value of `deltaX`. - **`absY`** (number) - The absolute value of `deltaY`. - **`velocity`** (number) - The absolute speed of the swipe in pixels per millisecond. - **`vxvy`** ([number, number]) - Per-axis velocity [deltaX/time, deltaY/time]. - **`dir`** (string) - The primary direction of the swipe ('Left', 'Right', 'Up', or 'Down'). ### Example Usage ```tsx import { useSwipeable, SwipeEventData } from 'react-swipeable'; function VelocityTracker() { const handlers = useSwipeable({ onSwiped: (data: SwipeEventData) => { const { event, initial, first, deltaX, deltaY, absX, absY, velocity, vxvy, dir, } = data; console.log(`Swiped ${dir}: ${absX}px horizontal, ${absY}px vertical`); console.log(`Speed: ${velocity.toFixed(3)} px/ms`); console.log(`Started at [${initial[0]}, ${initial[1]}]`); }, }); return
Swipe here
; } ``` ``` -------------------------------- ### Swipe Event Data Structure Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md The `SwipeEventData` object contains detailed information about the swipe gesture, including the source event, initial touch point, deltas, velocity, and direction. ```javascript { event, initial, // initial swipe [x,y] first, // true for the first event of a tracked swipe deltaX, // x offset (current.x - initial.x) deltaY, // y offset (current.y - initial.y) absX, // absolute deltaX absY, // absolute deltaY velocity, // √(absX^2 + absY^2) / time - "absolute velocity" (speed) vxvy, // [ deltaX/time, deltaY/time] - velocity per axis dir, // direction of swipe (Left|Right|Up|Down) } ``` -------------------------------- ### Swipe Event Data Structure Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md The data object passed to swipe event handlers, providing details about the swipe gesture. ```APIDOC ## Swipe Event Data ### Description Structure of the data object provided to swipe event handlers. ### Fields - `event`: The source event object. - `initial`: The initial [x, y] coordinates of the swipe. - `first`: Boolean, `true` if this is the first event of a tracked swipe. - `deltaX`: The change in the X coordinate (current.x - initial.x). - `deltaY`: The change in the Y coordinate (current.y - initial.y). - `absX`: The absolute value of `deltaX`. - `absY`: The absolute value of `deltaY`. - `velocity`: The absolute velocity of the swipe (speed). - `vxvy`: Velocity per axis [deltaX/time, deltaY/time]. - `dir`: The direction of the swipe (Left|Right|Up|Down). ``` -------------------------------- ### Carousel Reducer for State Management Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-pattern.mdx Implements a reducer function to manage the carousel's state transitions based on dispatched actions, handling previous, next, and stop sliding states. ```typescript function reducer(state: CarouselState, action: CarouselAction): CarouselState { switch (action.type) { case PREV: return { ...state, dir: PREV, sliding: true, pos: state.pos === 0 ? action.numItems - 1 : state.pos - 1 }; case NEXT: return { ...state, dir: NEXT, sliding: true, pos: state.pos === action.numItems - 1 ? 0 : state.pos + 1 }; case 'stopSliding': return { ...state, sliding: false }; default: return state; } } ``` -------------------------------- ### Replace preventDefaultTouchmoveEvent with preventScrollOnSwipe Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/v7-migration.md When migrating from v6 to v7, replace the `preventDefaultTouchmoveEvent` prop with `preventScrollOnSwipe` to maintain the same functionality. This change makes the prop's purpose more explicit. ```diff const handlers = useSwipeable({ - preventDefaultTouchmoveEvent: true, + preventScrollOnSwipe: true, }); ``` -------------------------------- ### Define Carousel Types and State Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-pattern.mdx Defines TypeScript types for carousel directions, state, and actions, ensuring type safety for carousel operations. ```typescript type Direction = typeof PREV | typeof NEXT; interface CarouselState { pos: number; sliding: boolean; dir: Direction; } type CarouselAction = | { type: Direction, numItems: number } | { type: 'stopSliding' }; ``` -------------------------------- ### Limit Swipe Gestures by Time with `swipeDuration` Source: https://context7.com/formidablelabs/react-swipeable/llms.txt The `swipeDuration` option discards swipes that exceed a specified time in milliseconds. This is useful for differentiating intentional flick gestures from slow drags. ```tsx import { useSwipeable } from 'react-swipeable'; function TimedSwipe() { const handlers = useSwipeable({ onSwipedLeft: () => console.log('fast left swipe (<250 ms)'), onSwipedRight: () => console.log('fast right swipe (<250 ms)'), onSwiped: () => console.log('any direction, within 250 ms'), swipeDuration: 250, // gestures lasting ≥250 ms produce no callbacks }); return
Quick-flick only
; } ``` -------------------------------- ### Dynamic Swipeable Component in React Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/examples.md Implement dynamic swipe behavior where scrollability can be controlled based on swipe actions and component state. The touch-action style is updated to 'none' or 'auto' accordingly. ```jsx const MySwipeableComponent = props => { const [stopScroll, setStopScroll] = useState(false); const handlers = useSwipeable({ onSwipeStart: () => setStopScroll(true), onSwiped: () => setStopScroll(false) }); return
Swipe here
; }; ``` -------------------------------- ### Define SVG Arrow Components Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/examples/simple-pattern.mdx These components render SVG arrows that visually indicate active states, providing user feedback for pattern recognition. ```typescript const UpArrow = ({active}: {active: boolean}) => ( ); const DownArrow = ({active}: {active: boolean}) => ( ); ``` -------------------------------- ### Prevent Native Scrolling with `preventScrollOnSwipe` Source: https://context7.com/formidablelabs/react-swipeable/llms.txt When `preventScrollOnSwipe` is `true`, `e.preventDefault()` is called on `touchmove` events for the swiping direction, preventing browser scrolling. This automatically sets the `touchmove` listener to `{ passive: false }`. ```tsx import { useSwipeable } from 'react-swipeable'; function NoScrollCarousel() { const handlers = useSwipeable({ onSwipedLeft: () => console.log('next slide'), onSwipedRight: () => console.log('prev slide'), preventScrollOnSwipe: true, // blocks vertical scroll while swiping horizontally trackTouch: true, }); return (
Slide 1
Slide 2
); } ``` -------------------------------- ### Event Handler Props for React Swipeable Source: https://github.com/formidablelabs/react-swipeable/blob/main/docs/docs/api.md These props are event handlers that are called during or after a swipe gesture. They receive `SwipeEventData` or a specific event object. ```javascript { onSwiped, // After any swipe (SwipeEventData) => void onSwipedLeft, // After LEFT swipe (SwipeEventData) => void onSwipedRight, // After RIGHT swipe (SwipeEventData) => void onSwipedUp, // After UP swipe (SwipeEventData) => void onSwipedDown, // After DOWN swipe (SwipeEventData) => void onSwipeStart, // Start of swipe (SwipeEventData) => void *see details* onSwiping, // During swiping (SwipeEventData) => void onTap, // After a tap ({ event }) => void // Pass through callbacks, event provided: ({ event }) => void onTouchStartOrOnMouseDown, // Called for `touchstart` and `mousedown` onTouchEndOrOnMouseUp, // Called for `touchend` and `mouseup` } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.