ReactJS - TouchEvent Handler



Touch events are important for enhancing the user experience, particularly with touch-sensitive devices like smartphones and tablets. We will look at several touch events, their types, and how to handle them in a React application.

Touch events are part of the larger family of web development UI events. These events let us record and respond to user activities like tapping, swiping, and pinching.

Syntax

<div
   onTouchStart={e => console.log('onTouchStart')}
   onTouchMove={e => console.log('onTouchMove')}
   onTouchEnd={e => console.log('onTouchEnd')}
   onTouchCancel={e => console.log('onTouchCancel')}
/>

Parameters

e − This is a React event object we can use with TouchEvent properties.

Types of TouchEvent

There are four major sorts of touch events to be aware of −

Sr.No Types & Description
1 touchstart

When a user places their finger on the touch surface, this event is triggered.

2 touchend

A touchend event happens when a user puts their finger off the surface or when the touch point goes off the edge of the surface.

3 touchmove

This happens when a user moves their finger across the surface. It constantly monitors the movement of the contact spot.

4 touchcancel

When a touch point is disturbed in some way, this message is sent.

Properties of TouchEvent

There are some touch event properties to be aware of −

Sr.No Properties & Description
1 altKey

Shows if the Alt key is pressed at the time of event.

2 ctrlKey

Indicates if the Ctrl key is clicked during the event.

3 changedTouches

A list of Touch objects showing touches that changed.

4 getModifierState(key)

A function that returns a boolean showing if a modifier key (e.g., Shift, Alt, or Ctrl) is pressed.

5 metaKey

shows if the Meta key is pressed during the event.

6 shiftKey

Indicates if the Shift key is clicked during the event.

7 touches

A list of Touch objects representing all current touches on the touch surface.

8 targetTouches

A list of Touch objects showing touches on the target element.

9 detail

Shows an integer value for additional event-specific information.

10 view

References the Window object that generated the event.

Examples

Example − Simple Touch App

We will create a simple React application to show the TouchEvent handlers with the below code. Here's a small React application that shows the touch events in the console −

import React from "react";

class App extends React.Component {
   render() {
      return (
         <div
            onTouchStart={(e) => console.log("onTouchStart")}
            onTouchMove={(e) => console.log("onTouchMove")}
            onTouchEnd={(e) => console.log("onTouchEnd")}
            onTouchCancel={(e) => console.log("onTouchCancel")}
            style={{
            width: "200px",
            height: "200px",
            backgroundColor: "lightblue",
            textAlign: "center",
            lineHeight: "200px"
            }}
         >
            TouchEvent
         </div>
      );
   }
}

export default App;

Output

This code generates the App React component. When one of the four touch events (touchstart, touchmove, touchend, and touchcancel) happens, the message is logged in the console. The component also provides a clickable <div> element with which we can interact on a touch-enabled device.

Example − Long Press App

The given React app, named "LongPressApp," is designed to detect a long press on a touch-enabled device. The app has a div element with a light blue background, and it spans 200 pixels both in width and height. When we touch and hold on the app for at least 1000 milliseconds, it logs a message to the console stating, "Long press detected."

import React from 'react';

class App extends React.Component {
   handleTouchStart = () => {
      this.longPressTimer = setTimeout(() => {
         console.log('Long press detected');
      }, 1000); // Adjust the duration for long press threshold
   };
   
   handleTouchEnd = () => {
      clearTimeout(this.longPressTimer);
   };   
   render() {
      return (
         <div
            onTouchStart={this.handleTouchStart}
            onTouchEnd={this.handleTouchEnd}
            style={{
               width: '200px',
               height: '200px',
               backgroundColor: 'lightblue',
               textAlign: 'center',
               lineHeight: '200px',
            }}
         >
            LongPressApp
         </div>
      );
   }
}

export default App;

Output

Open the app in a browser. Touch the app and keep your touch held for at least 1000 milliseconds. After the specified duration, we will be able to see the message "Long press detected" logged to the browser's console.

Example − Pinch Zoom App

The Pinch Zoom React app is designed to detect the start and end of a pinch gesture, typically used for zooming on touch-enabled devices. The app has a div element with a light blue background, spanning 200 pixels both in width and height. When a user starts a pinch gesture, it logs the message "Pinch started" to the console. Similarly, when the user ends the pinch gesture, it logs the message "Pinch ended."

import React from 'react';

class App extends React.Component {
   handleTouchStart = (e) => {
      if (e.touches.length === 2) {
         console.log('Pinch started');
      }
   };   
   handleTouchEnd = (e) => {
      if (e.touches.length < 2) {
         console.log('Pinch ended');
      }
   };
   
   render() {
      return (
         <div
            onTouchStart={this.handleTouchStart}
            onTouchEnd={this.handleTouchEnd}
            style={{
               width: '200px',
               height: '200px',
               backgroundColor: 'lightblue',
               textAlign: 'center',
               lineHeight: '200px',
            }}
         >
            PinchZoomApp
         </div>
      );
   }
}

export default App;

Output

Open the app in a browser. Use a touch-enabled device (like smartphone or tablet). Touch the app with two fingers simultaneously to trigger the "Pinch started" message. Release one or both fingers to trigger the "Pinch ended" message.

Summary

Touch events play an important role in React apps for creating engaging and interactive user interfaces, particularly on touch-sensitive devices. Understanding the various sorts of touch events and how to manage them allows us to deliver an effortless user experience for our website or app users.

reactjs_reference_api.htm
Advertisements