handsome
handsome

Reputation: 2402

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?

Upvotes: 3

Views: 3862

Answers (1)

handsome
handsome

Reputation: 2402

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')
}

Upvotes: 1

Related Questions