Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@andreisergiu98/react-swipeable

andreisergiu9856MIT5.6.2TypeScript support: included

React Swipe event handler component & hook

react swipe, react touch, react hook, touch, swipe, swipeable, react, hook, react-component

readme

React Swipeable

React swipe event handler component & hook

build status Coverage Status npm version npm downloads gzip size

Edit react-swipeable image carousel with hook

Github Pages Demo

Api

Use React-hooks or a Component and set your swipe(d) handlers.

import { useSwipeable, Swipeable } from 'react-swipeable'

Hook

const handlers = useSwipeable({ onSwiped: (eventData) => eventHandler, ...config })
return (<div {...handlers}> You can swipe here </div>)

Spread handlers onto the element you wish to track swipes inside of. Details below.

Component

<Swipeable onSwiped={(eventData) => eventHandler} {...config} >
  You can swipe here!
</Swipeable>

The Component <Swipeable> uses a <div> by default under the hood to attach event handlers to.

Props / Config Options

Event Handler Props

{
  onSwiped,          // Fired after any swipe
  onSwipedLeft,      // Fired after LEFT swipe
  onSwipedRight,     // Fired after RIGHT swipe
  onSwipedUp,        // Fired after UP swipe
  onSwipedDown,      // Fired after DOWN swipe
  onSwiping,         // Fired during any swipe
}

Event data

All Event Handlers are called with the below event data.

{
  event,          // source event
  initial,        // initial swipe [x,y]
  first,          // true for first event
  deltaX,         // x offset (initial.x - current.x)
  deltaY,         // y offset (initial.y - current.y)
  absX,           // absolute deltaX
  absY,           // absolute deltaY
  velocity,       // √(absX^2 + absY^2) / time
  dir,            // direction of swipe (Left|Right|Up|Down)
}

Configuration Props

{
  delta: 10,                             // min distance(px) before a swipe starts
  preventDefaultTouchmoveEvent: false,   // preventDefault on touchmove, *See Details*
  trackTouch: true,                      // track touch input
  trackMouse: false,                     // track mouse input
  rotationAngle: 0,                      // set a rotation angle
}

Component Specific Props

{
  nodeName: 'div',    // internally rendered component dom node
  innerRef            // callback ref for internal component dom node
}

None of the props/config options are required.

Hook details

  • Hook use requires react >= 16.8.0
  • The props contained in handlers are currently ref and onMouseDown
    • Please spread handlers as the props contained in it could change as react improves event listening capabilities
      • See #127 for some more context

preventDefaultTouchmoveEvent Details

preventDefaultTouchmoveEvent prevents the browser's touchmove event. Use this to stop the browser from scrolling while a user swipes.

  • e.preventDefault() is only called when:
    • preventDefaultTouchmoveEvent: true
    • trackTouch: true
    • the users current swipe has an associated onSwiping or onSwiped handler/prop

Example:

  • If a user is swiping right with <Swipable onSwipedRight={this.userSwipedRight} preventDefaultTouchmoveEvent={true} > then e.preventDefault() will be called, but if the user was swiping left then e.preventDefault() would not be called.

Please experiment with the example to test preventDefaultTouchmoveEvent.

passive listener issue

At the moment, the lighthouse audit is deducting 7 points from the best practices metric for "Does not use passive listeners to improve scrolling performance".

This will not affect behavior in the application, merely the score on the lighthouse audit.

This is currently being tracked in issue 167.

Version 5 Updates

React hooks have been released with 16.8.0 🎉

v5 of react-swipeable includes a hook, useSwipeable, that provides the same great functionality as <Swipeable>. See the useSwipeable hook in action with this codesandbox.

The component is still included and migration to v5 is straightforward. Please see the migration doc for more details including more info on the simplified api.

Development

Initial set up, with node 10+, run npm install.

Make changes/updates to the src/index.js file.

Please add tests if PR adds/changes functionality.

Verify updates with the examples

Build, run, and test examples locally: npm run start:examples

After the server starts you can then view the examples page with your changes at http://localhost:3000.

You can now make updates/changes to src/index.js and webpack will rebuild, then reload the page so you can test your changes!

License

MIT

changelog

5.5.0

5.4.0

  • Add initial property to eventData that supplies the inital [x, y] swipe value coordinates issue #150 and PR #131

5.3.0

5.2.3

5.2.2

5.2.0

5.1.0

  • Fix for preventDefaultTouchmoveEvent in safari issue #127 and PR #131
    • Thank you @JiiB and @bhj!
    • use ref callback for both <Swipeable> and useSwipeable to attach all touch event handlers
      • useSwipeable's returned handlers now contains a ref callback
      • Please see disscusion and comments in both #127 and #131 for more details and info.
        • fix avoids the passive: true issue from chrome document event listeners
        • fix avoids bug on safari where the touchmove event listener needs to be attached before a touchstart in order to be able to call e.preventDefault
  • removed touchHandlerOption prop
    • fix above deprecates this prop

5.0.0

  • Introduce react hook, useSwipeable
  • Core rewrite to simplify api and trim down bundled size
  • Add size-limit to help keep bundled size down
  • Add es export via "module": "es/index.js" to package.json
  • Add prettier code formating
  • [BREAKING] simplify handler event data to allow destructuring
    • onSwiped = ({ event, direction, absX, absY, velocity}) => console.log('swiped')
  • [BREAKING] deprecated onSwiping{Left|Right|Up|Down} handler props
    • can be replaced with direction/dir event data
    • onSwiping = ({ dir }) => console.log(`swiping - ${dir}`)
  • [BREAKING] deprecated props
    • flickThreshold
    • stopPropagation
    • disabled
  • [BREAKING] deprecated passing "rest" of props down
    • removed additional props besides the ones used by <Swipeable> from being passed down
      • only className and style get passed to <Swipeable>'s dom node, default div

4.3.0

  • Add rotationAngle prop. #103
    • will allow to set a rotation angle, e.g. for a four-player game on a tablet, where each player has a 90° turned view.
    • Thank you @Narquadah and @LarsKumbier!

4.2.2

  • fixed bug that happened when if either onSwiping or onSwiped were set we were not calling e.preventDefault() appropriately

4.2.0

  • Add support for calling preventDefault on Chrome 56+ via passive event support checking and manual event listener setup. #88

4.1.0

  • add disabled prop. #83
  • add innerRef prop that allows user to access to <Swipeable>'s inner dom node react ref. #82

4.0.1

  • fixed bug where delta was causing a swipe to not be tracked correctly, #74 , thanks @mctep

4.0.0

  • Major Change preventDefaultTouchmoveEvent defaults to false now #69
  • Major Change drop support for React 12 & 13, peerDependencies updated #64
    • prop-types added to dependencies #64
  • Major Change trackMouse now 'tracks' the swipe outside of the swipeable component, #67.
  • react 16 added to peerDependencies

3.9.0

3.8.0

  • Allow onMouseDown, onMouseUp, and onMouseMove props to fire appropriately again. #55, thanks @lochstar
  • Stop using this.state to track swipes, thanks @grantila for pointing out this change and submitting PR, #58. Should provide minor performance gains since Swipeable will no longer be calling this.setState internally.

3.7.0

3.6.0

  • add stopPropagation prop for all swipe events, defaults to false. See #46 for more info.

3.5.1

  • fix React 15.2.0 warning for unknown properties on DOM elements

3.5.0

  • Add configurable container element via nodeName prop, defaults to 'div'. See #24 and #40 for more info.

3.4.0

  • Add preventDefault while swiping when props onSwipedLeft, onSwipedRight, onSwipedUp, and onSwipedDown are present. See #21 and #37 for more info.

3.3.0

  • Adds velocity data to onSwiping callback
  • Updated the build process introducing ES2015 and babel

3.2.0

  • Adds preventDefaultTouchMoveEvent option, defaults to true

3.1.0

  • Adds isFLick to onSwipe events
  • Removes React as a peer dep
  • Adds onSwiping events

3.0.2

  • Fixes onSwipeDown and onSwipeUp events

3.0.1

  • Fixes vertical swiping

3.0.0

  • Refactors build into jsx.

2.1.0

  • Adds onSwipedUp, onSwipedRight, onSwipedDown, onSwipedLeft callbacks.

2.0

  • onFlick prop has been removed.

  • onSwipe now has a 4th argument for the callback Boolean isFlick

  • Added a prop flickThreshold which allows you to customize at what velocity a flick is detected.