rn-swiper-list

repository·main·Indexed 43 days ago

https://github.com/skipperlla/rn-swiper-list

A customizable Tinder-like swiper component for React Native version 3.0.0, optimized for smooth UI thread animations. It features support for multi-directional swiping, card flipping, and programmatic control via SwiperCardRefType. The library requires peer dependencies on react-native-reanimated, react-native-gesture-handler, and react-native-worklets.

Tokens
11.6K
Snippets
18
Records
25
Agent score
54%

What's inside rn-swiper-list

  1. Understand SpringConfig parameters

    main

    When providing a SpringConfig to customize animations, use the following parameters to define the physical properties of the spring:

    | Parameter                 | Type   | Description                                                                                                                                                |
    | :------------------------ | :----- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | damping                   | number | Controls the amount of damping in the spring. Higher values result in more damping, causing the animation to slow down more quickly.                       |
    | stiffness                 | number | Controls the stiffness of the spring. Higher values result in a stiffer spring, causing the animation to be more rigid and faster.                       |
    | mass                      | number | Controls the mass of the object being animated. Higher values result in a heavier object, causing the animation to be slower.                              |
    | overshootClamping         | bool   | If true, the spring animation will not overshoot its target value. This means the animation will stop exactly at the target value without bouncing.       |
    | restDisplacementThreshold | number | The threshold for the displacement of the spring below which the spring is considered to be at rest. Lower values result in a more precise stopping point. |
    | restSpeedThreshold        | number | The threshold for the speed of the spring below which the spring is considered to be at rest. Lower values result in a more precise stopping point.        |
  2. Understand callback execution timing and indexing

    main

    When implementing swipe logic, keep these two behaviors in mind:

    1. Callback Execution Timing: All swipe callbacks (onSwipeLeft, onSwipeRight, onSwipeTop, onSwipeBottom) are executed after the animation has been set up on the UI thread. This is designed to prevent race conditions where state changes might interfere with animations, ensuring smooth performance (especially on Android).

    2. Index Parameter: The index passed to swipe callbacks represents the card's position in the original data array, not its current position relative to an initialIndex. This ensures consistent indexing regardless of where the user starts in the stack.

  3. Restore a swipe session

    main

    To persist swipe history across component mounts, use initialIndex and restoredSwipes.

    • initialIndex: The index of the card that should be active on mount.
    • restoredSwipes: An array of objects representing cards already swiped. Each object must contain an index and a direction ('left', 'right', 'top', or 'bottom').

    Important Notes:

    • restoredSwipes is for seeding the swiper on mount; live updates to this prop after mounting are not supported.
    • Restoration is silent: onSwipeLeft, onSwipeRight, etc., are not triggered for restored entries.
    • To apply a different session, you must remount the swiper with new props.
    • swipeBack() can be used to rewind through the restored sequence immediately before the initialIndex.
    <Swiper
      ref={ref}
      data={data}
      initialIndex={3}
      restoredSwipes=[
        { index: 0, direction: 'right' },
        { index: 1, direction: 'left' },
        { index: 2, direction: 'top' },
      ]
      renderCard={(item) => <Card item={item} />}
    />
  4. Install rn-swiper-list

    main

    To use rn-swiper-list, install the package via yarn. Note that this library has peer dependencies on react-native-reanimated, react-native-gesture-handler, and react-native-worklets. You must complete the installation and configuration for these peer dependencies following their respective official documentation.

    yarn add rn-swiper-list
    
    yarn add react-native-reanimated react-native-gesture-handler react-native-worklets
  5. Implement Card Flipping with FlippedContent

    main

    To enable the card flipping feature, provide a FlippedContent prop to the SwipeableCard. This prop is a function that receives the current item and index and returns the component to be rendered on the back of the card.

    When FlippedContent is provided, the card can be flipped using the flipCard() method via its ref. The animation direction (X or Y axis) is determined by the direction prop.

    <SwipeableCard
      item={item}
      index={index}
      activeIndex={activeIndex}
      FlippedContent={(item, index) => (
        <View style={{ backgroundColor: 'red' }}>
          <Text>Back of card: {item.name}</Text>
        </View>
      )}
    >
      <View style={{ backgroundColor: 'blue' }}>
        <Text>Front of card</Text>
      </View>
    </SwipeableCard>
  6. Implement a Swiper list with rn-swiper-list

    main

    To use rn-swiper-list, import the Swiper component and provide a data array along with a renderCard function. The renderCard function receives the current item and its index, returning a JSX element to represent the card. You can also provide FlippedContent to define what appears when a card is flipped.

    Ensure your application is wrapped in GestureHandlerRootView from react-native-gesture-handler to enable swipe gestures.

    Note: The Swiper component can be controlled via a ref of type SwiperCardRefType to trigger programmatic swipes or flips.

    import React, { useCallback, useRef } from 'react';
    import { View, Text, Image } from 'react-native';
    import { GestureHandlerRootView } from 'react-native-gesture-handler';
    import { Swiper, type SwiperCardRefType } from 'rn-swiper-list';
    
    const IMAGES = [require('./image1.jpg'), require('./image2.jpg')];
    
    const App = () => {
      const ref = useRef<SwiperCardRefType>();
    
      const renderCard = useCallback((image: any) => (
        <View style={{ flex: 1, backgroundColor: 'white' }}>
          <Image source={image} style={{ flex: 1 }} />
        </View>
      ), []);
    
      const renderFlippedCard = useCallback((_: any, index: number) => (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Text>Flipped content {index}</Text>
        </View>
      ), []);
    
      return (
        <GestureHandlerRootView style={{ flex: 1 }}>
          <Swiper
            ref={ref}
            data={IMAGES}
            renderCard={renderCard}
            FlippedContent={renderFlippedCard}
            onSwipeRight={(index) => console.log('Swiped right:', index)}
          />
          <View>
            <Button title="Flip" onPress={() => ref.current?.flipCard()} />
            <Button title="Swipe Right" onPress={() => ref.current?.swipeRight()} />
          </View>
        </GestureHandlerRootView>
      );
    };
  7. Use SwiperCardRefType to control the Swiper component

    main

    You can control the Swiper component programmatically by attaching a ref with the type SwiperCardRefType. This allows you to trigger card actions from external buttons or logic.

    Available methods on the ref:

    • swipeRight(): Triggers a right swipe.
    • swipeLeft(): Triggers a left swipe.
    • swipeTop(): Triggers a top swipe.
    • swipeBottom(): Triggers a bottom swipe.
    • swipeBack(): Triggers a swipe back (undo).
    • flipCard(): Flips the current card.
    type SwiperCardRefType =
      | {
          swipeRight: () => void;
          swipeLeft: () => void;
          swipeBack: () => void;
          swipeTop: () => void;
          swipeBottom: () => void;
          flipCard: () => void;
        }
      | undefined;
  8. Use Swipe methods via Ref

    main

    The following methods are available on the Swiper instance (typically accessed via a ref) to programmatically trigger animations and actions.

    | props       | type     | description                                                      |
    | :---------- | :------- | :--------------------------------------------------------------- |
    | swipeBack   | callback | Resets the card position after a swipe event                     |
    | swipeRight  | callback | Animates the card to fling to the right and calls onSwipeRight   |
    | swipeLeft   | callback | Animates the card to fling to the left and calls onSwipeLeft     |
    | swipeTop    | callback | Animates the card to fling to the top and calls onSwipeTop       |
    | swipeBottom | callback | Animates the card to fling to the bottom and calls onSwipeBottom |
    | flipCard    | callback | Flips the card to show the back content                          |
  9. Configure SwipeableCard animations and gestures

    main

    The SwipeableCard component accepts several props to fine-tune the user experience:

    Swipe Direction Control

    • direction: Sets the primary swipe axis ('x' or 'y'). Defaults to 'y'.
    • disableLeftSwipe, disableRightSwipe, disableTopSwipe, disableBottomSwipe: Boolean flags to disable specific swipe directions.

    Animation Customization

    • flipDuration: Duration of the card flip animation in milliseconds.
    • swipeRightSpringConfig, swipeLeftSpringConfig, swipeTopSpringConfig, swipeBottomSpringConfig: Spring configurations for each swipe direction.
    • swipeBackXSpringConfig, swipeBackYSpringConfig: Spring configurations for returning the card to center.
    • translateXRange, translateYRange: Input ranges for rotation interpolation.
    • rotateInputRange, rotateOutputRange: Defines how the card rotates based on translation.

    Gesture Thresholds

    • swipeVelocityThreshold: If provided, a swipe will be triggered if the gesture velocity exceeds this value, even if the translation distance is small.

    Styling

    • cardStyle: Base style for the card container.
    • regularCardStyle: Style applied to the front of the card.
    • flippedCardStyle: Style applied to the back of the card.
    • overlayLabelContainerStyle: Style for the container of the overlay labels.
  10. Use Event Callbacks for swipe interactions

    main

    Use these event callbacks to respond to user interactions. Note that direction-based callbacks receive the card's index in the original data array and execute after animation setup.

    PropTypeDescriptionDefault
    onSwipeLeftfuncCalled when a card is swiped left.(cardIndex) => {}
    onSwipeRightfuncCalled when a card is swiped right.(cardIndex) => {}
    onSwipeTopfuncCalled when a card is swiped top.(cardIndex) => {}
    onSwipeBottomfuncCalled when a card is swiped bottom.(cardIndex) => {}
    onSwipedAllfuncCalled when all cards have been swiped.() => {}
    onSwipeStartfuncCalled when a swipe event starts.() => {}
    onSwipeEndfuncCalled when a swipe event ends.() => {}
    onSwipeActivefuncCalled when a swipe event is active.() => {}
    onIndexChangefuncCalled when the index of the card changes. Receives the index as a parameter.(cardIndex) => {}
    onPressfuncCalled when the card is pressed (tapped).() => {}
  11. Configure Rotation Animation Props

    main

    Use these props to control how the card translates and rotates during a swipe gesture. Most ranges are relative to the window dimensions.

    | props                                | type  | description                                                                                              | default                                    |
    | :----------------------------------- | :---- | :------------------------------------------------------------------------------------------------------- | :----------------------------------------- |
    | translateXRange                      | array | Translates the card horizontally.                                                                        | `[-windowWidth / 3, 0, windowWidth / 3]`   |
    | translateYRange                      | array | Translates the card vertically.                                                                          | `[-windowHeight / 3, 0, windowHeight / 3]` |
    | rotateInputRange                     | array | Array specifying the range of x values for rotation mapping.                                             | `[-windowWidth / 3, 0, windowWidth / 3]`   |
    | outputRotationRange                  | array | Array of rotation values corresponding to `rotateInputRange`.                                            | `[-Math.PI / 20, 0, Math.PI / 20]`         |
    | inputOverlayLabelTopOpacityRange     | array | Array defining the input range for animating the opacity of the top overlay label.                       | `[0, -(windowHeight / 3)]`                 |
    | outputOverlayLabelTopOpacityRange    | array | Array defining the output opacity values for the top overlay label, corresponding to the input range.    | `[0, 1]`                                   |
    | inputOverlayLabelBottomOpacityRange  | array | Array defining the input range for animating the opacity of the bottom overlay label.                      | `[0, windowHeight / 3]`                    |
    | outputOverlayLabelBottomOpacityRange | array | Array defining the output opacity values for the bottom overlay label, corresponding to the input range. | `[0, 1]`                                   |
  12. Configure Swipe Animation Spring Configs

    main

    You can customize the physics of swipe animations using SpringConfig objects. This allows you to control the speed, bounce, and weight of the swipe-back and fling animations.

    | props                                   | type         | description                                                    |
    | :-------------------------------------- | :----------- | :--------------------------------------------------------------- |
    | swipeBackXSpringConfig                  | SpringConfig | Spring configuration for swipe back animation on the X-axis.   |
    | swipeBackYSpringConfig                  | SpringConfig | Spring configuration for swipe back animation on the Y-axis.   |
    | swipeRightSpringConfig                   | SpringConfig | Spring configuration for swipe right animation on the X-axis.  |
    | swipeLeftSpringConfig                   | SpringConfig | Spring configuration for swipe left animation on the X-axis.    |
    | swipeTopSpringConfig                    | SpringConfig | Spring configuration for swipe top animation on the Y-axis.    |
    | swipeBottomSpringConfig                 | SpringConfig | Spring configuration for swipe bottom animation on the Y-axis. |