Skip to content

Instantly share code, notes, and snippets.

@Babadzhanov
Forked from hartzis/EventComponent.js
Created October 12, 2021 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Babadzhanov/6cc27db538b2ff8ccd6bc3e2b03414fb to your computer and use it in GitHub Desktop.
Save Babadzhanov/6cc27db538b2ff8ccd6bc3e2b03414fb to your computer and use it in GitHub Desktop.
Touch Event Handling React Component
import React from 'react';
export default class EventComponent extends React.Component {
constructor(props) {
super(props);
this._onTouchStart = this._onTouchStart.bind(this);
this._onTouchMove = this._onTouchMove.bind(this);
this._onTouchEnd = this._onTouchEnd.bind(this);
this.state = { swiped: false };
this._swipe = {};
this.minDistance = 50;
}
_onTouchStart(e) {
const touch = e.touches[0];
this._swipe = { x: touch.clientX };
this.setState({ swiped: false });
}
_onTouchMove(e) {
if (e.changedTouches && e.changedTouches.length) {
const touch = e.changedTouches[0];
this._swipe.swiping = true;
}
}
_onTouchEnd(e) {
const touch = e.changedTouches[0];
const absX = Math.abs(touch.clientX - this._swipe.x);
if (this._swipe.swiping && absX > this.minDistance ) {
this.props.onSwiped && this.props.onSwiped();
this.setState({ swiped: true });
}
this._swipe = {};
}
render() {
return (
<div
onTouchStart={this._onTouchStart}
onTouchMove={this._onTouchMove}
onTouchEnd={this._onTouchEnd}>
{`Component-${this.state.swiped ? 'swiped' : ''}`}
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment