Convert Figma logo to code with AI

callstack logoreact-native-pager-view

React Native wrapper for the Android ViewPager and iOS UIPageViewController.

2,657
411
2,657
162

Top Related Projects

React Native wrapper for the Android ViewPager and iOS UIPageViewController.

A complete native navigation solution for React Native

React Native's Animated library reimplemented

Routing and navigation for your React Native apps

UI Components Library for React Native

Quick Overview

React Native Pager View is a cross-platform ViewPager component for React Native. It provides a native paging experience for both Android and iOS platforms, allowing developers to create swipeable views with smooth animations and efficient performance.

Pros

  • Native implementation for both Android and iOS
  • Smooth and performant paging experience
  • Customizable with various props and styling options
  • Supports both horizontal and vertical paging

Cons

  • Limited documentation for advanced use cases
  • Some reported issues with RTL (Right-to-Left) support
  • Occasional conflicts with other React Native libraries
  • May require additional setup for certain features on iOS

Code Examples

  1. Basic usage:
import PagerView from 'react-native-pager-view';

<PagerView style={styles.pagerView} initialPage={0}>
  <View key="1">
    <Text>First page</Text>
  </View>
  <View key="2">
    <Text>Second page</Text>
  </View>
</PagerView>
  1. Using with custom styles and callbacks:
<PagerView
  style={styles.pagerView}
  initialPage={0}
  onPageSelected={e => console.log('Page selected:', e.nativeEvent.position)}
>
  {pages.map((page, index) => (
    <View key={index} style={styles.pageStyle}>
      <Text>{page.title}</Text>
    </View>
  ))}
</PagerView>
  1. Implementing a custom page indicator:
const [currentPage, setCurrentPage] = useState(0);

<View>
  <PagerView
    style={styles.pagerView}
    initialPage={0}
    onPageSelected={e => setCurrentPage(e.nativeEvent.position)}
  >
    {/* Page content */}
  </PagerView>
  <View style={styles.indicatorContainer}>
    {pages.map((_, index) => (
      <View
        key={index}
        style={[
          styles.indicator,
          index === currentPage && styles.activeIndicator,
        ]}
      />
    ))}
  </View>
</View>

Getting Started

  1. Install the package:

    npm install react-native-pager-view
    
  2. For iOS, install pods:

    cd ios && pod install
    
  3. Import and use in your React Native component:

    import PagerView from 'react-native-pager-view';
    
    function MyComponent() {
      return (
        <PagerView style={{flex: 1}}>
          <View key="1"><Text>Page 1</Text></View>
          <View key="2"><Text>Page 2</Text></View>
        </PagerView>
      );
    }
    

Competitor Comparisons

React Native wrapper for the Android ViewPager and iOS UIPageViewController.

Pros of react-native-pager-view

  • Native implementation for both Android and iOS platforms
  • Smooth performance and efficient memory usage
  • Supports both horizontal and vertical paging

Cons of react-native-pager-view

  • Limited customization options compared to some alternatives
  • May require additional setup for complex use cases
  • Potential compatibility issues with older React Native versions

Code Comparison

react-native-pager-view:

import PagerView from 'react-native-pager-view';

<PagerView style={styles.pagerView} initialPage={0}>
  <View key="1"><Text>First page</Text></View>
  <View key="2"><Text>Second page</Text></View>
</PagerView>

Both repositories appear to be the same project, so there isn't a different code example to compare. The usage and implementation would be identical for both.

Summary

react-native-pager-view is a popular library for implementing paging functionality in React Native applications. It offers native performance and supports both Android and iOS platforms. While it provides smooth scrolling and efficient memory usage, it may have some limitations in terms of customization and compatibility with older React Native versions. The library is well-maintained and widely used in the React Native community, making it a solid choice for developers looking to implement paging in their apps.

A complete native navigation solution for React Native

Pros of react-native-navigation

  • More comprehensive navigation solution with advanced features like deep linking and custom transitions
  • Better performance for complex navigation structures due to native implementation
  • Extensive documentation and community support

Cons of react-native-navigation

  • Steeper learning curve compared to simpler pager solutions
  • Requires additional setup and configuration
  • May introduce more dependencies and increase app size

Code Comparison

react-native-navigation:

Navigation.setRoot({
  root: {
    stack: {
      children: [
        { component: { name: 'Home' } },
        { component: { name: 'Profile' } }
      ]
    }
  }
});

react-native-pager-view:

<PagerView style={styles.pagerView} initialPage={0}>
  <View key="1"><Text>Page 1</Text></View>
  <View key="2"><Text>Page 2</Text></View>
</PagerView>

react-native-navigation offers a more structured approach to navigation, allowing for complex hierarchies and native transitions. react-native-pager-view, on the other hand, provides a simpler solution for swipeable views, which may be sufficient for basic navigation needs. The choice between the two depends on the complexity of your app's navigation requirements and the level of customization needed.

React Native's Animated library reimplemented

Pros of React Native Reanimated

  • More powerful and flexible animation system
  • Better performance for complex animations
  • Supports gesture-based animations

Cons of React Native Reanimated

  • Steeper learning curve
  • Larger library size
  • May be overkill for simple animations

Code Comparison

React Native Pager View:

<PagerView style={styles.pagerView} initialPage={0}>
  <View key="1"><Text>First page</Text></View>
  <View key="2"><Text>Second page</Text></View>
</PagerView>

React Native Reanimated:

const animatedStyle = useAnimatedStyle(() => {
  return {
    opacity: withTiming(isVisible.value ? 1 : 0),
    transform: [{ scale: withSpring(isVisible.value ? 1 : 0.5) }],
  };
});

return <Animated.View style={[styles.box, animatedStyle]} />;

React Native Pager View is specifically designed for creating swipeable page layouts, making it simpler to implement basic paging functionality. It's lightweight and easy to use for straightforward paging needs.

React Native Reanimated, on the other hand, is a more comprehensive animation library that offers greater control and flexibility for complex animations. It's particularly useful for creating fluid, interactive animations that respond to user gestures.

While React Native Pager View excels at its specific task of paging, React Native Reanimated provides a broader set of tools for various animation scenarios, making it more versatile but potentially more complex for simple use cases.

Routing and navigation for your React Native apps

Pros of react-navigation

  • Comprehensive navigation solution with support for various navigation patterns (stack, tab, drawer)
  • Extensive documentation and community support
  • Seamless integration with React Native's navigation APIs

Cons of react-navigation

  • Steeper learning curve due to its extensive feature set
  • Potentially larger bundle size compared to more focused solutions
  • May require additional configuration for complex navigation scenarios

Code Comparison

react-navigation:

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

react-native-pager-view:

import PagerView from 'react-native-pager-view';

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

react-navigation provides a more comprehensive navigation solution, while react-native-pager-view focuses specifically on paging functionality. The choice between the two depends on the project's specific navigation requirements and complexity.

UI Components Library for React Native

Pros of react-native-ui-lib

  • Comprehensive UI component library with a wide range of pre-built components
  • Customizable theming system for consistent styling across the app
  • Includes accessibility features and RTL support out of the box

Cons of react-native-ui-lib

  • Larger package size due to the extensive component library
  • Steeper learning curve for developers unfamiliar with the library's conventions
  • May require more setup and configuration compared to simpler libraries

Code Comparison

react-native-pager-view:

import PagerView from 'react-native-pager-view';

<PagerView style={styles.pagerView} initialPage={0}>
  <View key="1"><Text>First page</Text></View>
  <View key="2"><Text>Second page</Text></View>
</PagerView>

react-native-ui-lib:

import { View, Text, PageControl } from 'react-native-ui-lib';

<View>
  <PageControl numOfPages={2} currentPage={this.state.currentPage} />
  <Text>Current page content</Text>
</View>

While react-native-pager-view focuses specifically on paging functionality, react-native-ui-lib provides a more comprehensive set of UI components, including a PageControl component that can be used in conjunction with other view management solutions.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.x5.x and above
iOSiOS support
ViewPager1ViewPager2

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

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 to manually link the framework or link using Cocoapods by adding this to your Podfile:

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

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

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.

@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>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

PropDescriptionPlatform
initialPageIndex of initial page that should be selectedboth
scrollEnabled: booleanShould pager view scroll, when scroll enabledboth
onPageScroll: (e: PageScrollEvent) => voidExecuted 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) => voidFunction called when the page scrolling state has changedboth
onPageSelected: (e: PageSelectedEvent) => voidThis callback will be called once the ViewPager finishes navigating to the selected pageboth
pageMargin: numberBlank space to be shown between pagesboth
keyboardDismissMode: ('none' / 'on-drag')Determines whether the keyboard gets dismissed in response to a dragboth
orientation: OrientationSet horizontal or vertical scrolling orientation (it does not work dynamically)both
overScrollMode: OverScrollModeUsed to override default value of overScroll mode. Can be auto, always or never. Defaults to autoAndroid
offscreenPageLimit: numberSet 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: booleanAllows for overscrolling after reaching the end or very beginning or pages. Defaults to falseiOS
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 localeboth
MethodDescriptionPlatform
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

  • flex:1 does not work for child views, please use width: '100%', height: '100%' instead

  • [iOS]: In case of UIViewControllerHierarchyInconsistency error, please use below fix:

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

Preview

Android

horizontalvertical
ViewPagerViewPager

iOS

horizontalvertical
ViewPagerViewPager

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} />;

License

MIT