### Install Example Project Dependencies
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/README.md
Run this command to install dependencies for the example project. Ensure you are in the `example` folder after cloning the repository.
```bash
yarn install
```
--------------------------------
### Install Dependencies for macOS Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/apps/macos-example/README.md
Run these commands in sequence to install all necessary dependencies for the macOS example application.
```bash
yarn
```
```bash
bundle install && bundle exec pod install
```
```bash
yarn start
```
--------------------------------
### Build and Run macOS Example App
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/apps/macos-example/README.md
After installing dependencies, open the Xcode project and build the app to run it on a macOS simulator or device.
```bash
Open the MacOSExample project in Xcode and build the app to run it on a macOS simulator or device.
```
--------------------------------
### Basic Manual Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-manual-gesture.mdx
This example demonstrates a basic setup for a manual gesture using `useManualGesture`. It initializes gesture state and renders a view that can be interacted with.
```javascript
active.value = false;
},
});
return (
{trackedPointers.map((pointer, index) => (
))}
);
}
const styles = StyleSheet.create({
pointer: {
width: 60,
height: 60,
borderRadius: 30,
backgroundColor: 'red',
position: 'absolute',
marginStart: -30,
marginTop: -30,
},
});
```
--------------------------------
### Rotation Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-rotation-gesture.mdx
This is a full example demonstrating the usage of the rotation gesture. It includes setup and handling of rotation events.
```typescript
import React from 'react';
import { StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, { useSharedValue, withSpring, useAnimatedStyle, interpolate, Extrapolate } from 'react-native-reanimated';
const RotationGestureBasic = () => {
const rotation = useSharedValue(0);
const startRotation = useSharedValue(0);
const rotationGesture = Gesture.Rotation()
.onBegin(() => {
startRotation.value = rotation.value;
})
.onUpdate((event) => {
rotation.value = startRotation.value + event.rotation;
})
.onEnd(() => {
rotation.value = withSpring(0);
startRotation.value = 0;
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [
{
rotate: `${rotation.value}rad`,
},
],
}));
return (
);
};
const styles = StyleSheet.create({
container: {
width: 150,
height: 150,
backgroundColor: 'tomato',
borderRadius: 20,
},
});
export default RotationGestureBasic;
```
--------------------------------
### Install Dependencies with NPM
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/guides/troubleshooting.mdx
Run this command after modifying your `package.json` to apply the specified overrides and ensure a consistent installation of dependencies.
```bash
npm install
```
--------------------------------
### Install Dependencies
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/README.md
Installs project dependencies using Yarn.
```console
yarn install
```
--------------------------------
### Example Jest Configuration (package.json)
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/guides/testing.mdx
An alternative example of a `package.json` file showing the Jest configuration for React Native Gesture Handler.
```json
"jest": {
"preset": "@react-native/jest-preset",
"transformIgnorePatterns": [
"node_modules/(?!((jest-)?react-native|react-native-gesture-handler)/)"
],
"setupFiles": [
"react-native-gesture-handler/jestSetup.js"
]
}
```
--------------------------------
### Start Local Development Server
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/README.md
Starts a local development server for live previewing changes. The server typically opens in a browser window automatically.
```console
yarn start
```
--------------------------------
### Install Pods for iOS Development
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/fundamentals/installation.mdx
Before running your app on iOS, navigate to the ios directory and install the necessary pods.
```bash
cd ios && bundle install && bundle exec pod install && cd ..
```
--------------------------------
### Install Pods for macOS Development
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/fundamentals/installation.mdx
Before running your app on macOS, navigate to the macos directory and install the necessary pods.
```bash
cd macos && bundle install && bundle exec pod install && cd ..
```
--------------------------------
### Basic Animated Style Setup
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/guides/quickstart/_steps/step2.md
Set up shared values and animated styles using react-native-reanimated for gesture-driven animations. This example demonstrates how to animate scale and background color based on a shared value.
```jsx
import {
useAnimatedStyle,
useSharedValue,
withSpring,
} from 'react-native-reanimated';
export default function Ball() {
const isPressed = useSharedValue(false);
const offset = useSharedValue({ x: 0, y: 0 });
const animatedStyles = useAnimatedStyle(() => {
return {
transform: [
{ translateX: offset.value.x },
{ translateY: offset.value.y },
{ scale: withSpring(isPressed.value ? 1.2 : 1) },
],
backgroundColor: isPressed.value ? 'yellow' : 'blue',
};
});
// ...
}
```
--------------------------------
### Basic Hover Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-hover-gesture.mdx
Demonstrates the basic setup of the useHoverGesture hook within a GestureDetector and a View component. Ensure GestureHandlerRootView is used as the root component.
```javascript
import { View, StyleSheet } from 'react-native';
import {
GestureDetector,
GestureHandlerRootView,
useHoverGesture,
} from 'react-native-gesture-handler';
export default function App() {
const hoverGesture = useHoverGesture({});
return (
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
},
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Basic Native Gesture Setup
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/native-gesture.md
This example demonstrates how to set up a basic Native gesture and attach it to a GestureDetector. The Native gesture is used here to disable the ScrollView when a touch starts on a black section of a rectangle, allowing custom pan gestures within that section.
```jsx
import { View, ScrollView } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
const COLORS = ['red', 'green', 'blue', 'purple', 'orange', 'cyan'];
export default function App() {
// highlight-next-line
const native = Gesture.Native();
return (
);
}
function ScrollableContent({ scrollGesture }) {
return (
{COLORS.map((color) => (
))}
);
}
function Rectangle({ color, scrollGesture }) {
const pan = Gesture.Pan().blocksExternalGesture(scrollGesture);
return (
);
}
```
--------------------------------
### Full ReanimatedDrawerLayout Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/components/reanimated-drawer-layout.mdx
A comprehensive example demonstrating the usage of ReanimatedDrawerLayout, including gesture handling for opening the drawer.
```tsx
import React, { useRef } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {
GestureDetector,
GestureHandlerRootView,
useTapGesture,
} from 'react-native-gesture-handler';
import ReanimatedDrawerLayout,
DrawerType,
DrawerPosition,
DrawerLayoutMethods,
} from 'react-native-gesture-handler/ReanimatedDrawerLayout';
const DrawerPage = () => {
return (
Lorem ipsum
);
};
export default function ReanimatedDrawerExample() {
const drawerRef = useRef(null);
const tapGesture = useTapGesture({
onDeactivate: () => {
drawerRef.current?.openDrawer();
},
runOnJS: true,
});
return (
}
drawerPosition={DrawerPosition.LEFT}
drawerType={DrawerType.FRONT}>
Open drawer
);
}
const styles = StyleSheet.create({
drawerContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'pink',
},
innerContainer: {
flex: 1,
backgroundColor: 'white',
alignItems: 'center',
justifyContent: 'center',
gap: 20,
},
box: {
padding: 20,
backgroundColor: 'pink',
},
});
```
--------------------------------
### Install Gesture Handler with npm
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/fundamentals/installation.mdx
Use this command to install react-native-gesture-handler using npm.
```bash
npm install react-native-gesture-handler
```
--------------------------------
### Install Gesture Handler with Yarn
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/fundamentals/installation.mdx
Use this command to install react-native-gesture-handler using Yarn.
```bash
yarn add react-native-gesture-handler
```
--------------------------------
### Basic Gesture Handler Setup
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/guides/quickstart/_steps/step3.md
Wrap your app's root component with GestureHandlerRootView to enable gesture handling. This is a necessary setup step for the library to function correctly.
```jsx
import React from 'react';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
export default function App() {
return (
{/* Your app content here */}
);
}
```
--------------------------------
### Example Jest Configuration (jest.config.js)
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/guides/testing.mdx
A complete example of a `jest.config.js` file incorporating the necessary configurations for testing with React Native Gesture Handler.
```javascript
module.exports = {
preset: '@react-native/jest-preset',
transformIgnorePatterns: [
'node_modules/(?!((jest-)?react-native|react-native-gesture-handler)/)',
],
setupFiles: ['react-native-gesture-handler/jestSetup.js'],
};
```
--------------------------------
### Basic Tap Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-tap-gesture.mdx
This example demonstrates how to use the `useTapGesture` hook to recognize a single tap. It logs a message to the console when the tap is activated. Ensure `GestureHandlerRootView` is used as the root component.
```javascript
import { View, StyleSheet } from 'react-native';
import {
GestureDetector,
GestureHandlerRootView,
useTapGesture,
} from 'react-native-gesture-handler';
export default function App() {
const singleTap = useTapGesture({
onActivate: () => {
console.log('Single tap!');
},
});
return (
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
},
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Basic Hover Gesture Setup
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/hover-gesture.md
This snippet demonstrates the basic setup for the Hover gesture. It requires importing `GestureDetector` and `Gesture` from `react-native-gesture-handler` and then creating a `Gesture.Hover()` instance.
```jsx
import {GestureDetector, Gesture} from 'react-native-gesture-handler';
function App() {
// highlight-next-line
const hover = Gesture.Hover();
return (
);
}
```
--------------------------------
### Basic Long Press Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-long-press-gesture.mdx
Demonstrates a basic implementation of the long press gesture. This example shows how to use the gesture and its default configuration.
```jsx
import React from 'react';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import { View, Text, StyleSheet } from 'react-native';
const LongPressGestureBasic = () => {
const longPress = Gesture.LongPress()
.onStart(() => {
console.log('Long press started');
})
.onActive(() => {
console.log('Long press active');
})
.onEnd((event) => {
console.log('Long press ended', event);
});
return (
Press and hold me
);
};
const styles = StyleSheet.create({
container: {
width: 200,
height: 200,
backgroundColor: 'lightblue',
justifyContent: 'center',
alignItems: 'center',
},
});
export default LongPressGestureBasic;
```
--------------------------------
### Basic Long Press Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/long-press-gesture.md
This example demonstrates how to set up a basic long press gesture. It logs a message to the console when the gesture is successfully completed after a long press.
```jsx
import { View, StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
export default function App() {
// highlight-next-line
const longPressGesture = Gesture.LongPress().onEnd((e, success) => {
if (success) {
console.log(`Long pressed for ${e.duration} ms!`);
}
});
return (
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Setup GestureHandlerRootView
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/guides/quickstart/_steps/step1.md
Wrap your app's root component with GestureHandlerRootView to enable gesture handling. This is a required setup step for using the library.
```jsx
import { StyleSheet } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import Animated from 'react-native-reanimated';
export default function Ball() {
return (
);
}
const styles = StyleSheet.create({
ball: {
width: 100,
height: 100,
borderRadius: 100,
backgroundColor: 'blue',
alignSelf: 'center',
},
});
```
--------------------------------
### Tap Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/tap-gesture.md
This example demonstrates how to use the Gesture.Tap() API to recognize single and double taps.
```APIDOC
## Example
```jsx
import { View, StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
export default function App() {
// highlight-next-line
const singleTap = Gesture.Tap()
.maxDuration(250)
.onStart(() => {
console.log('Single tap!');
});
// highlight-next-line
const doubleTap = Gesture.Tap()
.maxDuration(250)
.numberOfTaps(2)
.onStart(() => {
console.log('Double tap!');
});
return (
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
```
--------------------------------
### Basic GestureDetector Usage
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/gesture-detector.md
This example demonstrates the basic setup of GestureDetector with a Tap gesture. Ensure you import Gesture and GestureDetector from 'react-native-gesture-handler'. The gesture is passed as a prop to GestureDetector, which then wraps the view that should respond to gestures.
```javascript
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
function App() {
const tap = Gesture.Tap();
return (
// highlight-next-line
// highlight-next-line
);
}
```
--------------------------------
### Basic Pan Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/pan-gesture.md
Demonstrates a basic pan gesture that moves a box horizontally. The gesture updates the box's position based on translation and animates it back to the start or end position on release.
```jsx
import { StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated,
useSharedValue,
withTiming,
useAnimatedStyle,
} from 'react-native-reanimated';
const END_POSITION = 200;
export default function App() {
const onLeft = useSharedValue(true);
const position = useSharedValue(0);
// highlight-next-line
const panGesture = Gesture.Pan()
.onUpdate((e) => {
if (onLeft.value) {
position.value = e.translationX;
} else {
position.value = END_POSITION + e.translationX;
}
})
.onEnd((e) => {
if (position.value > END_POSITION / 2) {
position.value = withTiming(END_POSITION, { duration: 100 });
onLeft.value = false;
} else {
position.value = withTiming(0, { duration: 100 });
onLeft.value = true;
}
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateX: position.value }],
}));
return (
// highlight-next-line
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Install Gesture Handler with Expo
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/fundamentals/installation.mdx
Use this command to install react-native-gesture-handler when working with Expo.
```bash
npx expo install react-native-gesture-handler
```
--------------------------------
### Fling Gesture Basic Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/fling-gesture.md
This example demonstrates how to use the Gesture.Fling() API to detect a fling gesture in the right direction and update an animated view's position.
```APIDOC
## Example
```jsx
import { StyleSheet } from 'react-native';
import {
Gesture,
GestureDetector,
Directions,
} from 'react-native-gesture-handler';
import Animated, {
useSharedValue,
useAnimatedStyle,
withTiming,
} from 'react-native-reanimated';
export default function App() {
const position = useSharedValue(0);
// highlight-next-line
const flingGesture = Gesture.Fling()
.direction(Directions.RIGHT)
.onStart((e) => {
position.value = withTiming(position.value + 10, { duration: 100 });
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateX: position.value }],
}));
return (
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
```
--------------------------------
### Basic Pinch Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/pinch-gesture.md
This example demonstrates a basic pinch gesture for scaling a view. It uses `useSharedValue` to track the current scale and `onUpdate` to update the scale based on the gesture's input. The `onEnd` callback saves the final scale for future gestures.
```jsx
import { StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated,
useSharedValue,
useAnimatedStyle,
} from 'react-native-reanimated';
export default function App() {
const scale = useSharedValue(1);
const savedScale = useSharedValue(1);
// highlight-next-line
const pinchGesture = Gesture.Pinch()
.onUpdate((e) => {
scale.value = savedScale.value * e.scale;
})
.onEnd(() => {
savedScale.value = scale.value;
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ scale: scale.value }],
}));
return (
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Install Dependencies with YARN
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/guides/troubleshooting.mdx
Execute this command after updating your `package.json` to enforce the defined resolutions and ensure a unified dependency tree.
```bash
yarn
```
--------------------------------
### Full Long Press Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-long-press-gesture.mdx
Provides a comprehensive example of the long press gesture, including configuration and event handling. This snippet is useful for understanding advanced usage and customization.
```jsx
import React, { useState } from 'react';
import {
GestureHandlerRootView,
GestureDetector,
Gesture,
} from 'react-native-gesture-handler';
import {
StyleSheet,
View,
Text,
useWindowDimensions,
Animated,
} from 'react-native';
const LongPressExample = () => {
const {
width,
height,
} = useWindowDimensions();
const [backgroundColor, setBackgroundColor] = useState('lightgreen');
const opacity = React.useRef(new Animated.Value(1)).current;
const longPress = Gesture.LongPress()
.minDuration(200)
.onStart(() => {
console.log('long press started');
})
.onTouchesDown(() => {
Animated.timing(opacity, {
toValue: 0.5,
duration: 50,
useNativeDriver: true,
}).start();
})
.onActive(() => {
console.log('long press active');
})
.onTouchesUp(() => {
Animated.timing(opacity, {
toValue: 1,
duration: 50,
useNativeDriver: true,
}).start();
})
.onEnd((event) => {
console.log('long press ended', event);
setBackgroundColor('plum');
});
return (
Press and hold me
);
};
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
borderRadius: 20,
},
});
export default LongPressExample;
```
--------------------------------
### Basic Pan Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-pan-gesture.mdx
This example demonstrates a basic pan gesture. It tracks the horizontal translation and resets the position when the gesture deactivates. Requires `GestureDetector`, `GestureHandlerRootView`, `usePanGesture`, `useSharedValue`, `withTiming`, and `useAnimatedStyle`.
```typescript
import {
StyleSheet,
} from 'react-native';
import {
GestureDetector,
GestureHandlerRootView,
usePanGesture,
} from 'react-native-gesture-handler';
import Animated, {
useSharedValue,
withTiming,
useAnimatedStyle,
} from 'react-native-reanimated';
export default function App() {
const position = useSharedValue(0);
const panGesture = usePanGesture({
onUpdate: (e) => {
position.value = e.translationX;
},
onDeactivate: () => {
position.value = withTiming(0, { duration: 100 });
},
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateX: position.value }],
}));
return (
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
},
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Tap Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/tap-gesture.md
Demonstrates how to configure and use both single and double tap gestures. Use Gesture.Exclusive to allow only one of the gestures to be recognized at a time.
```jsx
import { View, StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
export default function App() {
// highlight-next-line
const singleTap = Gesture.Tap()
.maxDuration(250)
.onStart(() => {
console.log('Single tap!');
});
// highlight-next-line
const doubleTap = Gesture.Tap()
.maxDuration(250)
.numberOfTaps(2)
.onStart(() => {
console.log('Double tap!');
});
return (
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Touchable Component Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/components/touchable.mdx
Shows how to use the Touchable component to create three different button styles: a base button, a RectButton-like button, and a BorderlessButton-like button. Includes basic styling and onPress handlers.
```javascript
import React from 'react';
import { StyleSheet, Text } from 'react-native';
import {
GestureHandlerRootView,
Touchable,
} from 'react-native-gesture-handler';
export default function TouchableExample() {
return (
{
console.log('BaseButton built with Touchable');
}}
style={[styles.button, { backgroundColor: '#7d63d9' }]}>
BaseButton
{
console.log('RectButton built with Touchable');
}}
style={[styles.button, { backgroundColor: '#4f9a84' }]}
underlayColor="black"
animationDuration={0}>
RectButton
{
console.log('BorderlessButton built with Touchable');
}}
style={[styles.button, { backgroundColor: '#5f97c8' }]}
activeOpacity={0.3}
animationDuration={0}>
BorderlessButton
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
gap: 20,
},
button: {
width: 200,
height: 70,
borderRadius: 15,
alignItems: 'center',
justifyContent: 'center',
},
buttonText: {
color: 'white',
fontSize: 14,
fontWeight: '600',
},
});
```
--------------------------------
### Reanimated Swipeable Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/components/reanimated_swipeable.mdx
This example demonstrates how to implement a swipeable component using Reanimated. It includes a custom right action that animates based on the swipe gesture's translation. Ensure GestureHandlerRootView is used to wrap your application.
```javascript
import React from 'react';
import { Text, StyleSheet } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import ReanimatedSwipeable from 'react-native-gesture-handler/ReanimatedSwipeable';
import Reanimated, {
SharedValue,
useAnimatedStyle,
} from 'react-native-reanimated';
function RightAction(prog: SharedValue, drag: SharedValue) {
const styleAnimation = useAnimatedStyle(() => {
console.log('showRightProgress:', prog.value);
console.log('appliedTranslation:', drag.value);
return {
transform: [{ translateX: drag.value + 50 }],
};
});
return (
Text
);
}
export default function Example() {
return (
Swipe me!
);
}
const styles = StyleSheet.create({
rightAction: { width: 50, height: 50, backgroundColor: 'purple' },
separator: {
width: '100%',
borderTopWidth: 1,
},
swipeable: {
height: 50,
backgroundColor: 'papayawhip',
alignItems: 'center',
},
});
```
--------------------------------
### Hover Gesture Basic Usage
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/hover-gesture.md
This example demonstrates the basic usage of the Hover gesture. It shows how to create a Hover gesture instance and attach it to a View using GestureDetector.
```APIDOC
## Hover Gesture Basic Usage
### Description
This code snippet shows how to use the `Gesture.Hover()` method to create a hover gesture and attach it to a `View` component using `GestureDetector`.
### Method
```jsx
import { GestureDetector, Gesture } from 'react-native-gesture-handler';
function App() {
// highlight-next-line
const hover = Gesture.Hover();
return (
);
}
```
### Remarks
- Do not rely on the `Hover` gesture to continue after the mouse button is clicked or the stylus touches the screen. If you need to handle both cases, compose it with the `Pan` gesture.
```
--------------------------------
### Basic Fling Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/fling-gesture.md
This example demonstrates a basic fling gesture that triggers an animation when a fling to the right occurs. It requires importing Gesture, GestureDetector, Directions from 'react-native-gesture-handler' and necessary components from 'react-native-reanimated'.
```jsx
import { StyleSheet } from 'react-native';
import {
Gesture,
GestureDetector,
Directions,
} from 'react-native-gesture-handler';
import Animated,
useSharedValue,
useAnimatedStyle,
withTiming,
} from 'react-native-reanimated';
export default function App() {
const position = useSharedValue(0);
// highlight-next-line
const flingGesture = Gesture.Fling()
.direction(Directions.RIGHT)
.onStart((e) => {
position.value = withTiming(position.value + 10, { duration: 100 });
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateX: position.value }],
}));
return (
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Basic Integration with Animated API
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/fundamentals/animated-interactions.mdx
This example demonstrates how to use `Animated.event` with `useNativeDriver: true` for gesture updates. Ensure `useAnimated` is set to `true` in the gesture configuration.
```jsx
import * as React from 'react';
import { Animated, StyleSheet, useAnimatedValue } from 'react-native';
import {
GestureHandlerRootView,
GestureDetector,
usePanGesture,
} from 'react-native-gesture-handler';
export default function App() {
const value = useAnimatedValue(0);
const event = Animated.event(
[{ nativeEvent: { handlerData: { translationX: value } } }],
{
useNativeDriver: true,
}
);
const gesture = usePanGesture({
// highlight-next-line
onUpdate: event,
// highlight-next-line
useAnimated: true,
});
return (
);
}
const styles = StyleSheet.create({
box: {
width: 150,
height: 150,
backgroundColor: '#b58df1',
},
});
```
--------------------------------
### Basic Fling Gesture Example
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-fling-gesture.mdx
This example demonstrates a basic fling gesture that moves a box to the right when a fling gesture is detected in that direction. It requires importing necessary components from react-native-gesture-handler and react-native-reanimated.
```javascript
import { StyleSheet } from 'react-native';
import {
GestureDetector,
GestureHandlerRootView,
Directions,
useFlingGesture,
} from 'react-native-gesture-handler';
import Animated,
useSharedValue,
useAnimatedStyle,
withTiming } from 'react-native-reanimated';
export default function App() {
const position = useSharedValue(0);
const flingGesture = useFlingGesture({
direction: Directions.RIGHT,
onActivate: () => {
position.value = withTiming(position.value + 10, { duration: 100 });
},
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateX: position.value }],
}));
return (
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
},
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
--------------------------------
### Pan Gesture Basic Usage
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/gestures/use-pan-gesture.mdx
This example demonstrates the basic usage of the `usePanGesture` hook to track horizontal translation and reset the position.
```APIDOC
## usePanGesture
### Description
A continuous gesture that recognizes and tracks panning (dragging) movements. It activates after an initial movement threshold is met.
### Configuration Options
- `onUpdate`: Callback function executed during the gesture's update.
- `onDeactivate`: Callback function executed when the gesture is deactivated.
### Example Usage
```javascript
import { StyleSheet } from 'react-native';
import {
GestureDetector,
GestureHandlerRootView,
usePanGesture,
} from 'react-native-gesture-handler';
import Animated, {
useSharedValue,
withTiming,
useAnimatedStyle,
} from 'react-native-reanimated';
export default function App() {
const position = useSharedValue(0);
const panGesture = usePanGesture({
onUpdate: (e) => {
position.value = e.translationX;
},
onDeactivate: () => {
position.value = withTiming(0, { duration: 100 });
},
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateX: position.value }],
}));
return (
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
},
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
```
--------------------------------
### Automatic Workletization of Gesture Callbacks
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/fundamentals/reanimated-interactions.mdx
This example demonstrates a gesture callback that will be automatically marked as a worklet by the Reanimated Babel plugin.
```jsx
const gesture = useTapGesture({
onBegin: () => {
console.log(_WORKLET);
},
});
```
--------------------------------
### Accessibility Example for Buttons
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/components/buttons.mdx
Demonstrates how to make buttons accessible by wrapping children in a View with 'accessible' and 'accessibilityRole="button"' props. The 'NotAccessibleButton' shows the incorrect implementation.
```tsx
const NotAccessibleButton = () => (
Foo
);
// Accessible:
const AccessibleButton = () => (
Bar
);
```
--------------------------------
### Memoizing Gesture Configuration
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/gesture.md
This example shows how to use `React.useMemo` to optimize gesture configurations. Memoizing gestures can reduce the overhead for Gesture Handler during updates, especially when callbacks depend on component state or props.
```jsx
import React from 'react';
function App() {
const gesture = React.useMemo(
() =>
Gesture.Tap().onStart(() => {
console.log('Number of taps:', tapNumber + 1);
setTapNumber((value) => value + 1);
}),
[tapNumber, setTapNumber]
);
// ...
}
```
--------------------------------
### Rotation Gesture Implementation
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/rotation-gesture.md
This example demonstrates how to use the `Gesture.Rotation()` API to create a rotation gesture handler. It tracks the rotation amount and updates an animated view accordingly.
```APIDOC
## Gesture.Rotation()
### Description
Creates a rotation gesture recognizer. This gesture is activated when fingers are placed on the screen and change position in a way that indicates rotation.
### Method Signature
```javascript
Gesture.Rotation()
```
### Callbacks
- `onUpdate`: Called when the gesture is updated. Provides an event object with `rotation`, `anchorX`, `anchorY`, and `velocity`.
- `onEnd`: Called when the gesture ends. Allows saving the final rotation value.
### Event Data
- `rotation` (number): Amount rotated in radians from the gesture's focal point.
- `velocity` (number): Instantaneous velocity of the gesture in points per second.
- `anchorX` (number): X coordinate of the gesture's central focal point.
- `anchorY` (number): Y coordinate of the gesture's central focal point.
### Example Usage
```jsx
import { StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, {
useSharedValue,
useAnimatedStyle,
} from 'react-native-reanimated';
export default function App() {
const rotation = useSharedValue(1);
const savedRotation = useSharedValue(1);
const rotationGesture = Gesture.Rotation()
.onUpdate((e) => {
rotation.value = savedRotation.value + e.rotation;
})
.onEnd(() => {
savedRotation.value = rotation.value;
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ rotateZ: `${(rotation.value / Math.PI) * 180}deg` }],
}));
return (
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
```
--------------------------------
### Test Pan Gesture Handler
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/guides/testing.mdx
This example demonstrates how to test a pan gesture handler. It simulates gesture events using `fireGestureHandler` and asserts that the `onBegin` and `onActivate` callbacks are called.
```tsx
test('Pan gesture', () => {
const onBegin = jest.fn();
const onStart = jest.fn();
const panGesture = renderHook(() =>
usePanGesture({
disableReanimated: true,
onBegin: (e) => onBegin(e),
onActivate: (e) => onStart(e),
})
).result.current;
fireGestureHandler(panGesture, [
{ oldState: State.UNDETERMINED, state: State.BEGAN },
{ oldState: State.BEGAN, state: State.ACTIVE },
{ oldState: State.ACTIVE, state: State.ACTIVE },
{ oldState: State.ACTIVE, state: State.END },
]);
expect(onBegin).toHaveBeenCalledTimes(1);
expect(onStart).toHaveBeenCalledTimes(1);
});
```
--------------------------------
### Long Press Gesture Basic Usage
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/legacy-gestures/long-press-gesture.md
This example demonstrates the basic usage of the LongPress gesture. It logs the duration of the long press when the gesture ends successfully.
```APIDOC
## LongPressGesture
A discrete gesture that activates when the corresponding view is pressed for a sufficiently long time.
### Example
```jsx
import { View, StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
export default function App() {
const longPressGesture = Gesture.LongPress().onEnd((e, success) => {
if (success) {
console.log(`Long pressed for ${e.duration} ms!`);
}
});
return (
);
}
const styles = StyleSheet.create({
box: {
height: 120,
width: 120,
backgroundColor: '#b58df1',
borderRadius: 20,
marginBottom: 30,
},
});
```
### Configuration Properties
#### `minDuration(value: number)`
Minimum time, expressed in milliseconds, that a finger must remain pressed on the corresponding view. The default value is 500.
#### `maxDistance(value: number)`
Maximum distance, expressed in points, that defines how far the finger is allowed to travel during a long press gesture. If the finger travels further than the defined distance and the gesture hasn't yet activated, it will fail to recognize the gesture. The default value is 10.
#### `mouseButton(value: MouseButton)` (Web & Android only)
Allows users to choose which mouse button should handler respond to. The enum `MouseButton` consists of the following predefined fields: `LEFT`, `RIGHT`, `MIDDLE`, `BUTTON_4`, `BUTTON_5`, `ALL`. Arguments can be combined using `|` operator, e.g. `mouseButton(MouseButton.LEFT | MouseButton.RIGHT)`. Default value is set to `MouseButton.LEFT`.
### Callbacks
Refer to [Base Event Callbacks](/docs/2.x/shared/base-gesture-callbacks) for common callbacks.
### Event Data
#### `x`
X coordinate, expressed in points, of the current position of the pointer relative to the view attached to the `GestureDetector`.
#### `y`
Y coordinate, expressed in points, of the current position of the pointer relative to the view attached to the `GestureDetector`.
#### `absoluteX`
X coordinate, expressed in points, of the current position of the pointer relative to the window. It is recommended to use `absoluteX` instead of `x` in cases when the view attached to the `GestureDetector` can be transformed as an effect of the gesture.
#### `absoluteY`
Y coordinate, expressed in points, of the current position of the pointer relative to the window. It is recommended to use `absoluteY` instead of `y` in cases when the view attached to the `GestureDetector` can be transformed as an effect of the gesture.
#### `duration`
Duration of the long press (time since the start of the gesture), expressed in milliseconds.
```
--------------------------------
### Integration with VirtualGestureDetector
Source: https://github.com/software-mansion/react-native-gesture-handler/blob/main/packages/docs-gesture-handler/docs/fundamentals/animated-interactions.mdx
This example shows how to use `Animated.event` with `VirtualGestureDetector` when `useNativeDriver` is set to `false`. Remember to set `disableReanimated: true` in the gesture configuration.
```jsx
import React from 'react';
import { View, StyleSheet, Animated, useAnimatedValue } from 'react-native';
import {
GestureHandlerRootView,
InterceptingGestureDetector,
usePanGesture,
VirtualGestureDetector,
} from 'react-native-gesture-handler';
export default function App() {
const value = useAnimatedValue(0);
const event = Animated.event([{ translationX: value }], {
useNativeDriver: false,
});
const panGesture = usePanGesture({
onUpdate: event,
disableReanimated: true,
});
return (
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
outerBox: {
backgroundColor: '#b58df1',
width: 150,
height: 150,
},
innerBox: {
width: 100,
height: 100,
backgroundColor: 'blue',
},
});
```