0
0
React Nativemobile~20 mins

Gesture Handler integration in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Swipeable Box
A screen with a colored box that you can swipe left or right. The box changes color based on swipe direction.
Target UI
┌─────────────────────────────┐
│ Swipe the box left or right │
│                             │
│        ┌───────────┐        │
│        │           │        │
│        │   BOX     │        │
│        │           │        │
│        └───────────┘        │
│                             │
└─────────────────────────────┘
Use react-native-gesture-handler to detect horizontal swipes on the box.
The box should start with a gray background.
Swiping right changes the box color to green.
Swiping left changes the box color to red.
The box should smoothly animate color changes.
Use functional components and hooks.
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, StyleSheet, Animated } from 'react-native';
import { GestureDetector, Gesture } from 'react-native-gesture-handler';

export default function SwipeableBox() {
  const [boxColor, setBoxColor] = useState('gray');

  // TODO: Define swipe gesture here

  return (
    <View style={styles.container}>
      <Text style={styles.instructions}>Swipe the box left or right</Text>
      {/* TODO: Wrap box with GestureDetector and apply gesture */}
      <Animated.View style={[styles.box, { backgroundColor: boxColor }]} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff'
  },
  instructions: {
    fontSize: 18,
    marginBottom: 20
  },
  box: {
    width: 150,
    height: 150,
    borderRadius: 10
  }
});
Task 1
Task 2
Task 3
Task 4
Solution
React Native
import React, { useState, useRef } from 'react';
import { View, Text, StyleSheet, Animated } from 'react-native';
import { GestureDetector, Gesture } from 'react-native-gesture-handler';

export default function SwipeableBox() {
  const [boxColor, setBoxColor] = useState('gray');
  const animatedColor = useRef(new Animated.Value(0)).current; // 0=gray, 1=green, -1=red

  const colorInterpolation = animatedColor.interpolate({
    inputRange: [-1, 0, 1],
    outputRange: ['red', 'gray', 'green']
  });

  const swipeGesture = Gesture.Pan()
    .onEnd(event => {
      if (event.translationX > 50) {
        setBoxColor('green');
        Animated.timing(animatedColor, {
          toValue: 1,
          duration: 300,
          useNativeDriver: false
        }).start();
      } else if (event.translationX < -50) {
        setBoxColor('red');
        Animated.timing(animatedColor, {
          toValue: -1,
          duration: 300,
          useNativeDriver: false
        }).start();
      } else {
        setBoxColor('gray');
        Animated.timing(animatedColor, {
          toValue: 0,
          duration: 300,
          useNativeDriver: false
        }).start();
      }
    });

  return (
    <View style={styles.container}>
      <Text style={styles.instructions}>Swipe the box left or right</Text>
      <GestureDetector gesture={swipeGesture}>
        <Animated.View style={[styles.box, { backgroundColor: colorInterpolation }]} />
      </GestureDetector>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff'
  },
  instructions: {
    fontSize: 18,
    marginBottom: 20
  },
  box: {
    width: 150,
    height: 150,
    borderRadius: 10
  }
});

This solution uses react-native-gesture-handler to detect horizontal swipe gestures on the box. We create a Pan gesture that listens for the end of the swipe. If the user swipes right more than 50 pixels, the box color changes to green. If swiped left more than 50 pixels, it changes to red. Otherwise, it resets to gray.

We use React Native's Animated.Value to smoothly interpolate the background color between red, gray, and green. The Animated.timing function animates the color change over 300 milliseconds.

The box is wrapped inside a GestureDetector component that applies the gesture to it. This setup ensures the box responds visually and interactively to user swipes.

Final Result
Completed Screen
┌─────────────────────────────┐
│ Swipe the box left or right │
│                             │
│        ┌───────────┐        │
│        │           │        │
│        │   BOX     │        │
│        │           │        │
│        └───────────┘        │
│                             │
└─────────────────────────────┘
Swiping the box right changes its color smoothly to green.
Swiping the box left changes its color smoothly to red.
Swiping less than 50 pixels resets the box color to gray.
Stretch Goal
Add a reset button below the box that resets the box color to gray when tapped.
💡 Hint
Use a TouchableOpacity with a Text label 'Reset' and onPress handler to set boxColor state to 'gray' and animate the color back.