Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.