Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect swipe left/right in React

I´m trying to detect swipe left-right but I´m having a problem for example if a user makes a swipe up or down and a little bit to one of the sides it detects it as a swipe left (for example)

constructor(props) {
    super(props)

    this.state = {
        initialClientX: 0,
        finalClientX: 0,
    }
}

handleTouchStart(event) {
    this.setState({
        initialClientX: event.nativeEvent.touches[0].clientX
    });
}

handleTouchMove(event) {
    this.setState({
        finalClientX: event.nativeEvent.touches[0].clientX
    });
}

handleTouchEnd() {
    if (this.state.finalClientX < this.state.initialClientX) {
        console.log('swipe left')
    }

    this.setState({
        initialClientX: 0,
        finalClientX: 0
    });
}

how can I make this not too sensitive? should I also keep track of clientY?

like image 244
handsome Avatar asked Feb 06 '26 14:02

handsome


1 Answers

I ended up checking also for clientY as well a threshold

if ((this.state.finalClientX > this.state.initialClientX)
    && (this.state.finalClientY - this.state.initialClientY < 10)) {
        console.log('swipe left')
}
like image 61
handsome Avatar answered Feb 08 '26 03:02

handsome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!