react-native-sheet-transitions

repository·main·Indexed 21 days ago

https://github.com/saulsharma/react-native-sheet-transitions

A React Native library for smooth transitions in sheet-based UI components. It provides a SheetProvider for state management, a useSheet hook to control scale transitions, and a SheetScreen component that supports gesture-driven scaling, sliding, and fading with configurable drag directions and spring-based animations.

Tokens
3.1K
Snippets
10
Records
11
Agent score
75%

What's inside react-native-sheet-transitions

  1. Setup the SheetProvider

    main

    Wrap your application (or the relevant part of your component tree) with the SheetProvider component to enable sheet transition state management. This provider manages the shared scale value used for transitions and provides the useSheet hook to child components.

    Props

    • children: The components to be wrapped.
    • resizeType (optional): Determines the resize behavior. Defaults to 'decremental'. Supported values are 'incremental' or 'decremental'.
    • enableForWeb (optional): A boolean to enable sheet transitions on web platforms. Defaults to false.
    import { SheetProvider } from 'react-native-sheet-transitions';
    
    function App() {
      return (
        <SheetProvider resizeType="decremental" enableForWeb={true}>
          <YourAppContent />
        </SheetProvider>
      );
    }
  2. Configure SheetScreen drag directions

    main

    You can control which swipe directions trigger the closing of the sheet using the dragDirections prop. This is useful if you want a sheet that only slides down or only slides sideways.

    By default, toBottom is set to true. If isScrollable is enabled, the component intelligently manages the interaction between scrolling and dragging (e.g., toBottom will only trigger if the user is at the top of the scrollable content).

    <SheetScreen
      onClose={handleClose}
      dragDirections={{
        toTop: false,
        toBottom: true,
        toLeft: false,
        toRight: false
      }}
    >
      {/* Content */}
    </SheetScreen>
  3. Configure SheetScreen spring animations

    main

    The springConfig prop allows you to customize the physics of the sheet's movement using react-native-reanimated spring settings. This affects how the sheet snaps back to its position or completes its closing animation.

    import { SpringConfig } from 'react-native-sheet-transitions';
    
    const mySpringConfig: SpringConfig = {
      damping: 20,
      stiffness: 90,
      mass: 1,
      restDisplacementThreshold: 0.01,
      restSpeedThreshold: 0.01,
    };
    
    // Usage
    <SheetScreen
      onClose={handleClose}
      springConfig={mySpringConfig}
    >
      {/* Content */}
    </SheetScreen>
  4. Use SheetProvider and useSheet to manage sheet state

    main

    The SheetProvider component acts as the context provider for the sheet system, and the useSheet hook allows you to interact with the sheet state (such as opening or closing sheets) from any child component within the provider's tree.

    import { SheetProvider, useSheet } from 'react-native-sheet-transitions';
    
    function App() {
      return (
        <SheetProvider>
          <MyComponent />
        </SheetProvider>
      );
    }
    
    function MyComponent() {
      const { openSheet } = useSheet();
      // ... use openSheet to trigger transitions
    }
  5. Use the useSheet hook

    main

    The useSheet hook allows you to access the sheet's transition state and control its scale from any component nested within a SheetProvider.

    Note: Calling useSheet outside of a SheetProvider will throw an error.

    Returned Object

    • scale: An Animated.SharedValue<number> representing the current scale of the sheet. Use this in useAnimatedStyle to apply scaling to your components.
    • setScale: A function (scale: number) => void used to trigger a scale transition.
      • On iOS, this triggers a spring animation with specific damping and stiffness.
      • On Android, this sets the scale value directly without a spring animation.
    • resizeType: The 'incremental' | 'decremental' configuration passed to the provider.
    • enableForWeb: A boolean indicating if transitions are enabled for the web platform.
    import { useSheet } from 'react-native-sheet-transitions';
    import Animated, { useAnimatedStyle } from 'react-native-reanimated';
    
    function MyComponent() {
      const { scale, setScale } = useSheet();
    
      const animatedStyle = useAnimatedStyle(() => ({
        transform: [{ scale: scale.value }],
      }));
    
      return (
        <Animated.View style={animatedStyle}>
          <Button title="Shrink" onPress={() => setScale(0.9)} />
          <Button title="Expand" onPress={() => setScale(1)} />
        </Animated.View>
      );
    }
  6. Configure SheetScreen props

    main

    The SheetScreen component is configured using the SheetScreenProps interface. Key properties include:

    • onClose: A callback function triggered when the sheet is closed.
    • scaleFactor: A number used to scale the screen during transitions.
    • dragThreshold: The distance required to trigger a drag gesture.
    • dragDirections: An object defining allowed drag directions via toTop, toBottom, toLeft, and toRight (boolean values).
    • style: An AnimatedStyleProp<ViewStyle> for styling the sheet.
    • opacityOnGestureMove: A boolean indicating if opacity should change during a drag gesture.
    • containerRadiusSync: A boolean to sync the border radius with the container.
    • initialBorderRadius: The starting border radius for the sheet.
    • disableSyncScaleOnDragDown: A boolean to prevent scale synchronization when dragging down.
    • customBackground: A React node to provide a custom background for the sheet.
    • springConfig: Local spring configuration for this specific screen.
    <SheetScreen 
      onClose={() => handleClose()} 
      dragDirections={{ toTop: true, toBottom: true }} 
      initialBorderRadius={20}
    >
      <MyContent />
    </SheetScreen>
  7. Use the SheetScreen component

    main

    The SheetScreen component is the primary UI element for rendering a sheet-style screen with gesture-driven transitions (scaling, sliding, and fading). It supports drag-to-close gestures in multiple directions, spring-based animations, and integration with scrollable content.

    Key Features

    • Gestures: Supports dragging to bottom, top, left, or right to close the sheet.
    • Scaling: Automatically scales the sheet (and optionally the background) during transitions. Scaling is primarily supported on iOS.
    • Scroll Integration: If isScrollable is enabled, the component uses a ScrollHandler to ensure gestures don't conflict with scrolling (e.g., dragging down only triggers when the user is at the top of the scroll view).
    • Lifecycle Callbacks: Provides hooks for various stages of the sheet's lifecycle (opening, closing, and threshold crossing).

    Configuration Props

    PropTypeDefaultDescription
    childrenReactNodeRequiredThe content to be rendered inside the sheet.
    onClose() => voidRequiredCallback triggered when the sheet is dismissed.
    scaleFactornumber0.83The scale of the sheet when fully open.
    dragThresholdnumber150The distance (pixels) a user must drag before the close action is triggered.
    springConfigSpringConfig{ damping: 15, ... }Configuration for the spring animations used during transitions.
    dragDirectionsDragDirections{ toBottom: true, ... }Defines which directions are valid for closing the sheet.
    isScrollablebooleanfalseEnables scroll-aware gesture handling (prevents accidental closing while scrolling).
    opacityOnGestureMovebooleanfalseIf true, the sheet's opacity decreases as the user drags it away.
    initialBorderRadiusnumber50The starting border radius of the sheet container.
    customBackgroundReactNodeundefinedAn optional component to render behind the sheet.
    onOpenStart / onOpenEnd() => voidundefinedCallbacks for the opening lifecycle.
    onCloseStart / onCloseEnd() => voidonCloseCallbacks for the closing lifecycle.
    onBelowThreshold() => voidundefinedCallback triggered when the drag distance is below the dragThreshold but the user has started moving.
    disableRootScalebooleanfalseIf true, prevents the background scaling effect on iOS.
    disableSheetContentResizeOnDragDownbooleanfalseIf true, prevents the sheet content from resizing during the drag-down gesture.
    import { SheetScreen } from 'react-native-sheet-transitions';
    
    function MySheet() {
      return (
        <SheetScreen
          onClose={() => console.log('Closed')}
          scaleFactor={0.9}
          dragDirections={{ toBottom: true, toTop: false, toLeft: false, toRight: false }}
          isScrollable={true}
        >
          <Text>Sheet Content</Text>
        </SheetScreen>
      );
    }
  8. Use SheetScreen for sheet content

    main

    The SheetScreen component is used to define the content and behavior of a sheet. It is typically used in conjunction with the SheetProvider to render specific sheet views during transitions.

    import { SheetScreen } from 'react-native-sheet-transitions';
    
    function MySheet() {
      return (
        <SheetScreen>
          {/* Your sheet content goes here */}
        </SheetScreen>
      );
    }
  9. Configure the SheetProvider

    main

    The SheetProvider component accepts the following props to configure the global behavior of sheets within its context:

    • children: The React nodes to be wrapped.
    • springConfig: An optional SpringConfig (aliased from WithSpringConfig) to define the spring physics for sheet transitions.
    • resizeType: Determines how the sheet behaves during resizing. Options are 'incremental' or 'decremental'.
    <SheetProvider springConfig={{ damping: 20 }} resizeType='incremental'>
      <App />
    </SheetProvider>
  10. Define drag directions for sheets

    main

    When configuring a SheetScreen, you can restrict the directions in which a user can drag the sheet using the DragDirections interface. This is useful for preventing accidental swipes in unintended directions.

    Properties:

    • toTop: Boolean
    • toBottom: Boolean
    • toLeft: Boolean
    • toRight: Boolean
    const dragDirections: DragDirections = {
      toTop: true,
      toBottom: false,
      toLeft: false,
      toRight: false
    };
  11. Reference core types: SheetScreenProps, SpringConfig, and DragDirections

    main

    The library exports several key types for configuring sheets and transitions:

    • SheetScreenProps: Configuration properties for the SheetScreen component.
    • SpringConfig: Configuration object for spring-based animations.
    • DragDirections: Defines the allowed directions for sheet dragging.