CodeBlanks Logo Icon CodeBlanks

react-native-gesture-handler

Learn the react-native-gesture-handler library.

react-native-gesture-handler

react-native-gesture-handler is a library that uses the native gesture engine. It runs smoother and more reliably than the built-in PanResponder; it is used especially with React Navigation.

It offers ready-made components like TapGestureHandler for taps and PanGestureHandler for drags. Each has callbacks like onHandlerStateChange.

TapGestureHandler

TapGestureHandler captures the tap gesture. It tracks the state with onHandlerStateChange; event.nativeEvent.state takes values like State.BEGAN, State.ACTIVE and State.END. These values tell which phase the gesture is in.

Usage: <TapGestureHandler onHandlerStateChange={onTap}><View /></TapGestureHandler>. It must have a child; the tap is captured on the child. When State.END arrives, the tap is considered complete.

Practice Wrap with a TapGestureHandler

Use a TapGestureHandler: return <TapGestureHandler onHandlerStateChange={onTap}><View /></TapGestureHandler>. onTap is already defined.

Starter code

App.js
import React from 'react';
import { TapGestureHandler, View } from 'react-native-gesture-handler';

export default function Tap() {
  const onTap = () => console.log('tap');
  // Wrap with a TapGestureHandler
  return <View />;
}

Sample solution

App.js
import React from 'react';
import { TapGestureHandler, View } from 'react-native-gesture-handler';

export default function Tap() {
  const onTap = () => console.log('tap');
  return (
    <TapGestureHandler onHandlerStateChange={onTap}>
      <View />
    </TapGestureHandler>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Library import

Question
import { TapGestureHandler } from '____';
Answer
import { TapGestureHandler } from 'react-native-gesture-handler';

Explanation: TapGestureHandler comes from this library.

2 Match the gesture-handler concepts

Term Meaning
TapGestureHandler Tap gesture
PanGestureHandler Drag gesture
onHandlerStateChange State change
react-native-gesture-handler Library

3 Why is react-native-gesture-handler preferred?

  • Fewer features
  • Only iOS
  • Changes color
  • Native engine, smoother Correct answer

Explanation: With the native gesture engine it runs smoother.

All lessons in Intermediate