callstack / react-native-pager-view

React Native wrapper for the Android ViewPager and iOS UIPageViewController.
MIT License
2.76k stars 422 forks source link
android hacktoberfest ios react-native

react-native-pager-view ViewPager

npm package Lean Core Extracted License

Lint iOS Build Android Build

This component allows the user to swipe left and right through pages of data. Under the hood it is using the native Android ViewPager and the iOS UIPageViewController implementations. See it in action!


ViewPager


Versions

4.x 5.x and above
iOS iOS support
ViewPager1 ViewPager2

Migration

In version 6.x support for transitionStyle property has been dropped. More information here.

"@react-native-community/viewpager" library has been changed to react-native-pager-view. Here you can find more information, how to migrate pager view to the latest version

Getting started

Bun:

bun add react-native-pager-view

Yarn:

yarn add react-native-pager-view

Linking

>= 0.60

Autolinking will just do the job.

< 0.60

Mostly automatic

react-native link react-native-pager-view

Manual linking

Manually link the library on iOS
Follow the [instructions in the React Native documentation](https://facebook.github.io/react-native/img/linking-libraries-ios#manual-linking) to manually link the framework or link using [Cocoapods](https://cocoapods.org) by adding this to your `Podfile`: ```ruby pod 'react-native-pager-view', :path => '../node_modules/react-native-pager-view' ```
Manually link the library on Android
Make the following changes: #### `android/settings.gradle` ```groovy include ':react-native-pager-view' project(':react-native-pager-view').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-pager-view/android') ``` #### `android/app/build.gradle` ```groovy dependencies { ... implementation project(':react-native-pager-view') } ``` #### `android/app/src/main/.../MainApplication.java` On top, where imports are: Add `import com.reactnativepagerview.PagerViewPackage;` Add the `PagerViewPackage` class to your list of exported packages. ```java @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new PagerViewPackage() ); } ```

Usage

import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import PagerView from 'react-native-pager-view';

const MyPager = () => {
  return (
    <PagerView style={styles.pagerView} initialPage={0}>
      <View key="1">
        <Text>First page</Text>
      </View>
      <View key="2">
        <Text>Second page</Text>
      </View>
    </PagerView>
  );
};

const styles = StyleSheet.create({
  pagerView: {
    flex: 1,
  },
});

Attention: Note that you can only use View components as children of PagerView (cf. folder /example) . For Android if View has own children, set prop collapsable to false https://reactnative.dev/docs/view#collapsable-android, otherwise react-native might remove those children views and and its children will be rendered as separate pages

Advanced usage

For advanced usage please take a look into our example project

API

Prop Description Platform
initialPage Index of initial page that should be selected both
scrollEnabled: boolean Should pager view scroll, when scroll enabled both
onPageScroll: (e: PageScrollEvent) => void Executed when transitioning between pages (ether because the animation for the requested page has changed or when the user is swiping/dragging between pages) both
onPageScrollStateChanged: (e: PageScrollStateChangedEvent) => void Function called when the page scrolling state has changed both
onPageSelected: (e: PageSelectedEvent) => void This callback will be called once the ViewPager finishes navigating to the selected page both
pageMargin: number Blank space to be shown between pages both
keyboardDismissMode: ('none' / 'on-drag') Determines whether the keyboard gets dismissed in response to a drag both
orientation: Orientation Set horizontal or vertical scrolling orientation (it does not work dynamically) both
overScrollMode: OverScrollMode Used to override default value of overScroll mode. Can be auto, always or never. Defaults to auto Android
offscreenPageLimit: number Set the number of pages that should be retained to either side of the currently visible page(s). Pages beyond this limit will be recreated from the adapter when needed. Defaults to RecyclerView's caching strategy. The given value must either be larger than 0. Android
overdrag: boolean Allows for overscrolling after reaching the end or very beginning or pages. Defaults to false iOS
layoutDirection: ('ltr' / 'rtl' / 'locale') Specifies layout direction. Use ltr or rtl to set explicitly or locale to deduce from the default language script of a locale. Defaults to locale both
Method Description Platform
setPage(index: number) Function to scroll to a specific page in the PagerView. Invalid index is ignored. both
setPageWithoutAnimation(index: number) Function to scroll to a specific page in the PagerView. Invalid index is ignored. both
setScrollEnabled(scrollEnabled: boolean) A helper function to enable/disable scroll imperatively. The recommended way is using the scrollEnabled prop, however, there might be a case where a imperative solution is more useful (e.g. for not blocking an animation) both

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

Known Issues

requestAnimationFrame(() => refPagerView.current?.setPage(index));

Preview

Android

horizontal vertical
ViewPager ViewPager

iOS

horizontal vertical
ViewPager ViewPager

Reanimated onPageScroll handler

An example can be found here

Instructions

To attach reanimated handler with onPageScroll follow the below steps.

// 1. Define the handler
function usePageScrollHandler(handlers, dependencies) {
  const { context, doDependenciesDiffer } = useHandler(handlers, dependencies);
  const subscribeForEvents = ['onPageScroll'];

  return useEvent(
    (event) => {
      'worklet';
      const { onPageScroll } = handlers;
      if (onPageScroll && event.eventName.endsWith('onPageScroll')) {
        onPageScroll(event, context);
      }
    },
    subscribeForEvents,
    doDependenciesDiffer
  );
}

// 2. Attach the event handler
import PagerView from 'react-native-pager-view';
import Animated from 'react-native-reanimated';
const AnimatedPagerView = Animated.createAnimatedComponent(PagerView);

const pageScrollHandler = usePageScrollHandler({
  onPageScroll: (e) => {
    'worklet';
    offset.value = e.offset;
    console.log(e.offset, e.position);
  },
});

<AnimatedPagerView onPageScroll={pageScrollHandler} />;

usePagerView Hook Usage

The usePagerView hook is a convenient way to manage the state and control the behavior of the <PagerView /> component. It provides functions and variables to interact with the pager, such as navigating between pages and enabling/disabling scrolling.

Below is an example of how to use the usePager hook:

export function PagerHookExample() {
  const { AnimatedPagerView, ref, ...rest } = usePagerView({ pagesAmount: 10 });

  return (
    <SafeAreaView style={styles.container}>
      <AnimatedPagerView
        testID="pager-view"
        ref={ref}
        style={styles.PagerView}
        initialPage={0}
        layoutDirection="ltr"
        overdrag={rest.overdragEnabled}
        scrollEnabled={rest.scrollEnabled}
        onPageScroll={rest.onPageScroll}
        onPageSelected={rest.onPageSelected}
        onPageScrollStateChanged={rest.onPageScrollStateChanged}
        pageMargin={10}
        orientation="horizontal"
      >
        {useMemo(
          () =>
            rest.pages.map((_, index) => (
              <View
                testID="pager-view-content"
                key={index}
                style={{
                  flex: 1,
                  backgroundColor: '#fdc08e',
                  alignItems: 'center',
                  padding: 20,
                }}
                collapsable={false}
              >
                <LikeCount />
                <Text testID={`pageNumber${index}`}>
                  {`page number ${index}`}
                </Text>
              </View>
            )),
          [rest.pages]
        )}
      </AnimatedPagerView>
      <NavigationPanel {...rest} />
    </SafeAreaView>
  );
}

How the Example Works:

Conclusion

The usePager hook makes it easy to handle pagination with dynamic views. This example demonstrates how to set up a simple paginated interface where users can scroll through pages, interact with page elements, and control the pager with external navigation.

License

MIT