react-native-swipeable-item

repository·main·Indexed 43 days ago

https://github.com/computerjazz/react-native-swipeable-item

A React Native component for creating native-feeling swipeable rows with underlays and overlays, powered by Reanimated and React Native Gesture Handler. Version 2.0.9 is compatible with react-native-draggable-flatlist and provides the SwipeableItem component, the useSwipeableItemParams hook, and imperative control via refs to programmatically open or close items.

Tokens
4.7K
Snippets
9
Records
12
Agent score
6%

What's inside react-native-swipeable-item

  1. Install react-native-swipeable-item

    main

    To use react-native-swipeable-item, you must first ensure that react-native-reanimated and react-native-gesture-handler are installed and configured in your project according to their respective documentation. Then, install the package using npm or yarn.

    # 1. Install reanimated and react-native-gesture-handler first
    # 2. Install swipeable-item
    npm install react-native-swipeable-item
    # or
    yarn add react-native-swipeable-item
  2. How Overlay and Underlay rendering works

    main

    The SwipeableItem uses a layered architecture:

    1. Underlays: Rendered via renderUnderlayLeft and renderUnderlayRight. These are placed behind the main item and become visible as the user swipes. They are managed via UnderlayContext.
    2. Overlay: The main children of the component are the primary layer. However, you can also provide a renderOverlay function to render additional content on top of the main children. This is managed via OverlayContext.

    This separation allows you to build complex interactions where the background (underlay) contains actions like 'Delete' or 'Archive', while the foreground (overlay) can contain interactive elements that respond to the swipe progress.

  3. Troubleshoot gesture conflicts with Draggable Flatlist

    main

    If you are using react-native-swipeable-item inside react-native-draggable-flatlist and find that the list is not scrolling correctly, it is likely because the gesture handlers are capturing touches unintentionally.

    Solution: Increase the activationThreshold (or activationDistance) to ensure the swipe gesture only engages after a certain amount of movement, allowing the list's scroll gesture to take precedence for smaller movements.

  4. Use the useSwipeableItemParams hook

    main

    The useSwipeableItemParams hook provides access to the context of the swipeable item within its underlay or overlay components. This allows you to trigger actions like open() or close() and react to the current percentOpen animation value.

    • In an Underlay: The open() method automatically knows which direction to open based on the underlay's side. percentOpen refers to the progress of that specific direction.
    • In an Overlay: You must specify the direction using openLeft() or openRight(). percentOpen provides both percentOpenLeft and percentOpenRight values.
    function MyUnderlayComponent() {
      // Underlay components "know" which direction to open
      const swipeableItemParams = useSwipeableItemParams();
      return <TouchableOpacity onPress={swipeableItemParams.open} />;
    }
    
    function MyOverlayComponent() {
      // Overlay components get defaults filled in for `open()` and `percentOpen` params.
      const swipeableItemParams = useSwipeableItemParams();
      return <TouchableOpacity onPress={swipeableItemParams.openLeft} />;
    }
  5. Control SwipeableItem imperatively with instance methods

    main

    You can programmatically open or close a SwipeableItem using a ref. This is useful for triggering swipes from outside the component's own render tree.

    • open(direction, snapIndex?, options?): Opens the item in the specified OpenDirection. Returns a Promise that resolves once the opening animation completes.
    • close(options?): Closes the item. Returns a Promise that resolves once the closing animation completes.
    const itemRef = useRef<SwipeableItemImperativeRef>(null)
    
    // ...
    
    <SwipeableItem ref={itemRef} />
    
    // ...
    
    itemRef.current?.open(OpenDirection.LEFT)
  6. Configure SwipeableItem props

    main

    The SwipeableItem component accepts several props to control the swipe behavior, underlays, and snap points.

    Note on Naming: The library names props based on the swipe direction. A swipe left reveals the renderUnderlayLeft component (the content on the left side of the row).

    | Name                  | Type                                                                    | Description                                                                                                                                                                                                                                                            |
    | :-------------------- | :---------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
    | `renderUnderlayLeft`  | `RenderUnderlay`                                                        | Component to be rendered underneath row on left swipe.                                                                                                                                                                                                                                               |
    | `renderUnderlayRight` | `RenderUnderlay`                                                        | Component to be rendered underneath row on right swipe.                                                                                                                                                                                                                                              |
    | `snapPointsLeft`      | `number[]`                                                              | Pixel values left-swipe snaps to (eg. `[100, 300]`)
    | `snapPointsRight`     | `number[]`                                                              | Pixel values right-swipe snaps to (eg. `[100, 300]`)
    | `renderOverlay`       | `RenderOverlay`                                                         | Component to be rendered on top. Use if you need access to programmatic open/close methods. May alternatively pass children to SwipeableItem.                                                                                                                                                |
    | `onChange`            | `(params: { openDirection: OpenDirection, snapPoint: number }) => void` | Called when row is opened or closed.                                                                                                                                                                                                                                                 |
    | `swipeEnabled`        | `boolean`                                                               | Enable/disable swipe. Defaults to `true`.                                                                                                                                                                                                                                             |
    | `activationThreshold` | `number`                                                                | Distance finger must travel before swipe engages. Defaults to 20.                                                                                                                                                                                                                                      |
    | `swipeDamping`        | `number`                                                               | How much swipe velocity determines snap position. A smaller number means swipe velocity will have a larger effect and row will swipe open more easily. Defaults to `10`.                                                                                                                                  |
  7. Access unified swipe state with useSwipeableItemParams

    main

    The useSwipeableItemParams hook provides a unified way to access the swipe state. It is designed to work correctly whether called from an overlay or an underlay context. It provides an open function that automatically determines the correct direction based on the current context or a provided OpenDirection.

    import { useSwipeableItemParams, OpenDirection } from 'react-native-swipeable-item';
    
    const MyComponent = () => {
      const { open, percentOpen } = useSwipeableItemParams();
    
      // 'open' will use the direction from the current context (underlay or overlay)
      // or you can specify it explicitly:
      const openRight = () => open(50, OpenDirection.RIGHT);
    
      return <View style={{ transform: [{ scale: percentOpen.value }] }} />;
    };
  8. Access swipe state with useOverlayParams

    main

    Use the useOverlayParams hook inside a component rendered by renderOverlay to access the current swipe state, including the direction and the percentage of how open the item is. This allows you to create interactive overlay elements that react to the swipe gesture.

    import { useOverlayParams } from 'react-native-swipeable-item';
    
    const MyOverlay = () => {
      const { percentOpen, open } = useOverlayParams();
    
      return (
        <View style={{ opacity: percentOpen }}>
          <Button title="Action" onPress={() => open(0)} />
        </View>
      );
    };
  9. Use the SwipeableItem component

    main

    The SwipeableItem component allows you to create swipeable list items in React Native. It supports rendering an overlay (on top of the item) and underlays (visible behind the item when swiped). You can control the swipe behavior using snapPointsLeft and snapPointsRight arrays, and interact with the item imperatively via a ref.

    import SwipeableItem, { OpenDirection } from 'react-native-swipeable-item';
    import { useRef } from 'react';
    
    const MyComponent = () => {
      const swipeableRef = useRef<SwipeableItemImperativeRef>(null);
    
      return (
        <SwipeableItem
          ref={swipeableRef}
          item={someData}
          snapPointsLeft={[50, 100]}
          snapPointsRight={[50]}
          renderOverlay={(params) => (
            <View>{/* Overlay content */}</View>
          )}
          renderUnderlayLeft={(params) => (
            <View>{/* Underlay content for left swipe */}</View>
          )}
          onChange={({ openDirection, snapPoint }) => {
            console.log(openDirection, snapPoint);
          }}
        >
          <View>{/* Main item content */}</View>
        </SwipeableItem>
      );
    };
  10. Control SwipeableItem imperatively via ref

    main

    You can control the open/close state of a SwipeableItem using a ref of type SwipeableItemImperativeRef. This is useful for triggering swipes programmatically (e.g., from a button press).

    Methods:

    • open(openDirection: OpenDirection, snapPoint?: number, options?: { animated?: boolean }): Promise<void>: Opens the item in the specified direction to a specific snap point.
    • close(options?: { animated?: boolean }): Promise<void>: Closes the item.
    // To open to the right at the first snap point:
    swipeableRef.current?.open(OpenDirection.RIGHT, 50);
    
    // To close:
    swipeableRef.current?.close();
  11. Access swipe state with useUnderlayParams

    main

    Use the useUnderlayParams hook inside a component rendered by renderUnderlayLeft or renderUnderlayRight to access the state specific to that underlay. This is useful for animating underlay content based on the swipe progress.

    import { useUnderlayParams } from 'react-native-swipeable-item';
    
    const MyUnderlay = () => {
      const { percentOpen, direction } = useUnderlayParams();
    
      return (
        <View>
          <Text>Swiping {direction}</Text>
          <Text>Progress: {percentOpen.value}</Text>
        </View>
      );
    };
  12. Configure SwipeableItem props

    main

    The following props are available for the SwipeableItem component:

    PropTypeDescription
    itemTThe data item associated with this swipeable component.
    childrenReactNodeThe main content of the item (the overlay layer).
    renderOverlayRenderOverlay<T>Function to render content on top of the item.
    renderUnderlayLeftRenderUnderlay<T>Function to render content visible when swiping left.
    renderUnderlayRightRenderUnderlay<T>Function to render content visible when swiping right.
    onChange(params: { openDirection: OpenDirection; snapPoint: number; }) => voidCallback triggered when the swipe state changes.
    overSwipenumberAmount of extra distance allowed beyond the max snap point.
    animationConfigPartial<WithSpringConfig>Configuration for the spring animation.
    activationThresholdnumberDistance required to start the swipe gesture.
    swipeEnabledbooleanWhether swiping is enabled.
    snapPointsLeftnumber[]Array of snap points for left swipes (negative values).
    snapPointsRightnumber[]Array of snap points for right swipes (positive values).
    swipeDampingnumberDamping factor used to calculate velocity-based snapping.