React Native Paper Onboarding

repository·master·Indexed 21 days ago

https://github.com/gorhom/react-native-paper-onboarding

A Material Design inspired UI slider for React Native that provides smooth, animated onboarding transitions between slides. It supports customizable slide content, background colors, and navigation indicators, with programmatic control via next() and previous() methods. Requires react-native-reanimated, react-native-gesture-handler, and react-native-svg as peer dependencies.

Tokens
3.3K
Snippets
7
Records
13
Agent score
75%

What's inside @gorhom/paper-onboarding

  1. Install Paper Onboarding

    master

    Install the @gorhom/paper-onboarding package using yarn or npm.

    Important: This library has peer dependencies that must be installed separately. You must also install react-native-reanimated, react-native-gesture-handler, and react-native-svg, and follow their respective installation instructions for your environment.

    yarn add @gorhom/paper-onboarding
    # or
    npm install @gorhom/paper-onboarding
  2. Use PaperOnboarding in your application

    master

    To use PaperOnboarding, provide an array of PaperOnboardingItemType objects to the data prop. Each item represents a slide in the onboarding flow. You can customize the title, description, background color, and provide custom components for images, icons, or content.

    import PaperOnboarding, {PaperOnboardingItemType} from "@gorhom/paper-onboarding";
    
    const data: PaperOnboardingItemType[] = [
      {
        title: 'Hotels',
        description: 'All hotels and hostels are sorted by hospitality rating',
        backgroundColor: '#698FB8',
        image: /* IMAGE COMPONENT */,
        icon: /* ICON COMPONENT */,
        content: /* CUSTOM COMPONENT */,
      },
      {
        title: 'Banks',
        description: 'We carefully verify all banks before add them into the app',
        backgroundColor: '#6CB2B8',
        image: /* IMAGE COMPONENT */,
        icon: /* ICON COMPONENT */,
        content: /* CUSTOM COMPONENT */,
      },
      {
        title: 'Stores',
        description: 'All local stores are categorized for your convenience',
        backgroundColor: '#9D8FBF',
        image: /* IMAGE COMPONENT */,
        icon: /* ICON COMPONENT */,
        content: /* CUSTOM COMPONENT */,
      },
    ];
    
    const Screen = () => {
      const handleOnClosePress = () => console.log('navigate to other screen')
      return (
        <PaperOnboarding
          data={data}
          onCloseButtonPress={handleOnClosePress}
        />
      )
    }
  3. Configure PaperOnboarding props

    master

    The PaperOnboarding component accepts several props to control the behavior and appearance of the onboarding flow:

    • data (Required): An array of PaperOnboardingItemType objects defining the slides.
    • safeInsets: Safe area insets (e.g., from react-native-safe-area-context). Defaults to {top: 50, bottom: 50, left: 50, right: 50}.
    • direction: The pan gesture direction. Accepts 'horizontal' (default) or 'vertical'.
    • indicatorSize: The width and height of the indicator. Defaults to 40.
    • indicatorBackgroundColor: Background color of the indicator. Defaults to white.
    • indicatorBorderColor: Border color of the indicator. Defaults to white.
    • titleStyle: Style object to override the title text style for all slides.
    • descriptionStyle: Style object to override the description text style for all slides.
    • closeButton: A custom component to replace the default close button.
    • closeButtonText: Text for the close button. Defaults to close.
    • closeButtonTextStyle: Style object for the close button text.
    • onCloseButtonPress: Callback function triggered when the close button is pressed.
    • onIndexChange: Callback function triggered when the slide index changes.
  4. Configure PaperOnboardingItemType

    master

    Each object in the data array must follow the PaperOnboardingItemType structure to define individual slides:

    • backgroundColor (Required): The background color for the slide.
    • content: Custom slide content that replaces the default content. Can be a React.ReactNode or a function receiving PageContentProps.
    • image: Custom image cover component.
    • icon: Custom indicator icon component.
    • title: The title text for the slide.
    • description: The description text for the slide.
    • titleStyle: Style object to override the title style for this specific slide.
    • descriptionStyle: Style object to override the description style for this specific slide.
    • showCloseButton: Boolean to show/hide the close button on this slide. Note: The last page always shows the close button.
  5. Configure Metro for the example project

    master

    The metro.config.js in the example/ directory is configured to handle peer dependencies correctly within a monorepo-like structure. It uses watchFolders to include the project root and a resolver configuration to prevent multiple versions of peer dependencies from being loaded.

    Specifically, it:

    1. Adds the project root to watchFolders.
    2. Uses blacklistRE to ignore peer dependency modules located in the root node_modules.
    3. Uses extraNodeModules to alias those same peer dependencies to the versions installed within the example/node_modules directory.
    4. Configures the transformer with inlineRequires: true for optimized loading.
    const path = require('path');
    const blacklist = require('metro-config/src/defaults/blacklist');
    const escape = require('escape-string-regexp');
    const pak = require('../package.json');
    
    const root = path.resolve(__dirname, '..');
    
    const modules = Object.keys({
      ...pak.peerDependencies,
    });
    
    module.exports = {
      projectRoot: __dirname,
      watchFolders: [root],
    
      resolver: {
        blacklistRE: blacklist(
          modules.map(
            m => new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
          )
        ),
        extraNodeModules: modules.reduce((acc, name) => {
          acc[name] = path.join(__dirname, 'node_modules', name);
          return acc;
        }, {}),
      },
    
      transformer: {
        getTransformOptions: async () => ({
          transform: {
            experimentalImportSupport: false,
            inlineRequires: true,
          },
        }),
      },
    };
  6. Configure the close button with PaperOnboardingCloseButtonConfig

    master

    Use PaperOnboardingCloseButtonConfig to customize the behavior and appearance of the close button.

    Properties:

    • closeButton: A custom component or ReactNode to replace the default close button.
    • closeButtonText: The text displayed on the button. Defaults to 'close'.
    • closeButtonTextStyle: Style for the close button text.
    • onCloseButtonPress: Callback function executed when the button is pressed.
  7. Configure indicators with PaperOnboardingIndicatorConfig

    master

    Use PaperOnboardingIndicatorConfig to style the navigation dots/indicators.

    Properties:

    • indicatorSize: The width and height of the indicator. Defaults to 40.
    • indicatorBackgroundColor: The background color of the indicator. Defaults to 'white'.
    • indicatorBorderColor: The border color of the indicator. Defaults to 'white'.
  8. Use the PaperOnboarding component

    master

    The PaperOnboarding component is the main entry point for the library. It is exported as the default export from the package. You can import it and use it to render an onboarding flow in your React Native application.

    import PaperOnboarding from '@gorhom/paper-onboarding';
    
    // Usage within a component
    <PaperOnboarding ... />
  9. Configure the PaperOnboarding component with PaperOnboardingProps

    master

    The main PaperOnboarding component accepts PaperOnboardingProps to control the flow and appearance of the onboarding experience.

    Properties:

    • data: (Required) An array of PaperOnboardingItemType objects representing the pages.
    • direction: The pan gesture direction. Can be 'horizontal' or 'vertical'. Defaults to 'horizontal'.
    • onIndexChange: A callback function triggered when the current page index changes. Receives the new index as a number.
    • safeInsets: Insets for safe area handling (top, bottom, left, right). Defaults to {top: 50, bottom: 50, left: 50, right: 50}.
    • Inherited Configs: You can also pass partial configurations for indicators and the close button directly to the main component:
      • indicatorSize: Number for indicator size.
      • indicatorBackgroundColor: Color for indicator background.
      • indicatorBorderColor: Color for indicator border.
      • closeButtonText: Text for the close button.
      • onCloseButtonPress: Callback for when the close button is pressed.
    <PaperOnboarding
      data={data}
      direction="horizontal"
      onIndexChange={(index) => console.log(index)}
      indicatorSize={40}
      closeButtonText="Finish"
      onCloseButtonPress={() => handleClose()}
    />
  10. Customize slide content with PageContentProps

    master

    If you provide a custom component to the content property of a PaperOnboardingItemType, it will receive PageContentProps. This allows you to build highly customized slide layouts that react to the onboarding progress.

    PageContentProps includes:

    • index: The current page index.
    • animatedFocus: An Animated.Node<number> representing the focus/progress of the current page, useful for creating parallax or fade effects.
    • title, titleStyle, description, descriptionStyle, image: The specific properties defined in the item for that page.
    interface MyCustomContent = React.FC<PageContentProps>;
    
    const MyCustomContent: MyCustomContent = ({ index, animatedFocus, title }) => {
      return (
        <View>
          <Animated.Text style={{ opacity: animatedFocus }}>
            {title}
          </Animated.Text>
        </View>
      );
    };
    
    // Usage in data:
    // { ..., content: MyCustomContent }