Skip to content

Instantly share code, notes, and snippets.

@rista404
Created April 11, 2018 10:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rista404/291157e9fb2807178d408547cf643b78 to your computer and use it in GitHub Desktop.
Save rista404/291157e9fb2807178d408547cf643b78 to your computer and use it in GitHub Desktop.
import React from 'react'
//...
class Slider extends React.Component {
//...
render() {
return (
<WithSwipe toLeftSwipe={this.next} toRightSwipe={this.prev}>
//...
</WithSwipe>
)
}
}
import React from 'react'
export default class WithSwipe extends React.Component {
xDown = null
yDown = null
handleTouchStart = evt => {
this.xDown = evt.touches[0].clientX
this.yDown = evt.touches[0].clientY
}
handleTouchMove = evt => {
const xDown = this.xDown
const yDown = this.yDown
if (!xDown || !yDown) return
const xUp = evt.touches[0].clientX
const yUp = evt.touches[0].clientY
const xDiff = xDown - xUp
const yDiff = yDown - yUp
if (Math.abs(xDiff) > Math.abs(yDiff)) {
if (xDiff > 0) {
/* left swipe */
this.props.toLeftSwipe()
} else {
/* right swipe */
this.props.toRightSwipe()
}
}
/* reset values */
this.xDown = null
this.yDown = null
}
render() {
const { children } = this.props
return (
<div
onTouchMove={e => this.handleTouchMove(e)}
onTouchStart={e => this.handleTouchStart(e)}
>
{children}
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment