diff --git a/MIGRATION.md b/MIGRATION.md deleted file mode 100644 index 139d6627..00000000 --- a/MIGRATION.md +++ /dev/null @@ -1,16 +0,0 @@ -## Migration Guide - -# 5.x -> 6.x -Due to some issues, support for the `transitionStyle` property, which was iOS only, has been dropped. In version **6.x** passing it will not have any effect. - -# 5.0.x -> 5.1.x -Before: -```js -import ViewPager from '@react-native-community/viewpager' -import type { ViewPagerOnPageScrollEventData,ViewPagerOnPageSelectedEventData } from '@react-native-community/viewpager'; -``` - -After: -```js -import PagerView from 'react-native-pager-view'; -import type { PagerViewOnPageScrollEventData, PagerViewOnPageSelectedEventData } from 'react-native-pager-view'; diff --git a/README.md b/README.md index d607a3af..13a9420b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ - React Native PagerView @@ -9,13 +8,13 @@ [![npm package](https://badge.fury.io/js/react-native-pager-view.svg)](https://badge.fury.io/js/react-native-pager-view) [![Lean Core Extracted](https://img.shields.io/badge/Lean%20Core-Extracted-brightgreen.svg)](https://github.com/facebook/react-native/issues/23313) -[![License](https://img.shields.io/github/license/callstack/react-native-pager-view?color=blue)](https://github.com/callstack/react-native-pager-view/blob/master/LICENSE) +[![License](https://img.shields.io/github/license/callstack/react-native-pager-view?color=blue)](https://github.com/callstack/react-native-pager-view/blob/main/LICENSE) [![Lint](https://github.com/callstack/react-native-pager-view/actions/workflows/main.yml/badge.svg)](https://github.com/callstack/react-native-pager-view/actions/workflows/main.yml) [![iOS Build](https://github.com/callstack/react-native-pager-view/actions/workflows/ios.yml/badge.svg)](https://github.com/callstack/react-native-pager-view/actions/workflows/ios.yml) [![Android Build](https://github.com/callstack/react-native-pager-view/actions/workflows/android.yml/badge.svg)](https://github.com/callstack/react-native-pager-view/actions/workflows/android.yml) -This component allows the user to swipe left and right through pages of data. Under the hood it is using the native [Android ViewPager](https://developer.android.com/jetpack/androidx/releases/viewpager2) and the [iOS UIPageViewController](https://developer.apple.com/documentation/uikit/uipageviewcontroller) implementations. [See it in action!](https://github.com/callstack/react-native-pager-view#preview) +`PagerView` lets users swipe left and right (or up and down) through pages of content. It is a native component: on Android it renders a [Jetpack Compose pager](https://developer.android.com/develop/ui/compose/layouts/pager), and on iOS a [SwiftUI paged `TabView`](https://developer.apple.com/documentation/swiftui/tabview). [See it in action!](#preview)

@@ -24,99 +23,29 @@ This component allows the user to swipe left and right through pages of data. Un
-## Migration - -> [!WARNING] -> From version **7.x** only new architecture is supported. - -In version **6.x** support for `transitionStyle` property has been dropped. More information [here](https://github.com/callstack/react-native-pager-view/blob/master/MIGRATION.md). - -`"@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](https://github.com/callstack/react-native-pager-view/blob/master/MIGRATION.md) - -## 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: +## Installation -#### `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') +```sh +npm install react-native-pager-view +# or +yarn add react-native-pager-view +# or +bun add react-native-pager-view ``` -#### `android/app/build.gradle` +The library is autolinked. On iOS, install the pods afterwards: -```groovy -dependencies { - ... - implementation project(':react-native-pager-view') -} +```sh +cd ios && pod install ``` -#### `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 -```js -import React from 'react'; +```tsx import { StyleSheet, View, Text } from 'react-native'; import PagerView from 'react-native-pager-view'; -const MyPager = () => { +export function MyPager() { return ( @@ -127,7 +56,7 @@ const MyPager = () => { ); -}; +} const styles = StyleSheet.create({ pagerView: { @@ -136,77 +65,103 @@ const styles = StyleSheet.create({ }); ``` -**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 , otherwise react-native might remove those children views and its children will be rendered as separate pages +Each direct child of `PagerView` becomes one page and is stretched to fill the pager. Give every child a unique `key`. + +To control the pager from code, keep a ref and call its [methods](#methods): + +```tsx +const ref = useRef(null); -## Advanced usage +// ... + + {pages} +; -For advanced usage please take a look into our [example project](https://github.com/callstack/react-native-pager-view/blob/master/example/src/BasicPagerViewExample.tsx) +// later +ref.current?.setPage(2); +``` + +For more examples, see the [example app](example/src): nested pagers, keyboard handling, tab views, pagination dots, carousels and more. ## 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 (either 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 | +### Props -## Contributing +| Prop | Description | Platform | +| -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | :------: | +| `initialPage: number` | Index of the page that is selected on mount. | both | +| `scrollEnabled: boolean` | Whether the user can swipe between pages. Defaults to `true`. | both | +| `orientation: 'horizontal' \| 'vertical'` | Scroll direction. Defaults to `horizontal`. Changing it after mount is not supported. | both | +| `layoutDirection: 'ltr' \| 'rtl' \| 'locale'` | Layout direction. Use `ltr` or `rtl` to set it explicitly, or `locale` to follow `I18nManager.isRTL`. Defaults to `locale`. | both | +| `pageMargin: number` | Blank space between pages. | both | +| `keyboardDismissMode: 'none' \| 'on-drag'` | Whether the keyboard is dismissed when the user drags the pager. Defaults to `none`. | both | +| `onPageScroll: (e: PagerViewOnPageScrollEvent) => void` | Called while moving between pages, either from a swipe or from an animated `setPage`. `e.nativeEvent` contains `position` and `offset`. | both | +| `onPageSelected: (e: PagerViewOnPageSelectedEvent) => void` | Called once the pager settles on a page, and once on mount for `initialPage`. `e.nativeEvent.position` is the selected index. | both | +| `onPageScrollStateChanged: (e: PageScrollStateChangedNativeEvent) => void` | Called when the scroll state changes. `e.nativeEvent.pageScrollState` is `idle`, `dragging` or `settling`. | both | +| `overdrag: boolean` | Allows bouncing past the first and last page. Defaults to `false`. | iOS | +| `offscreenPageLimit: number` | Number of pages kept composed on each side of the visible page. When unset, the Compose pager default is used. | Android | +| `overScrollMode: 'auto' \| 'always' \| 'never'` | Overscroll effect at the edges. `never` disables the effect. Defaults to `auto`. | Android | -See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. +`PagerView` also accepts all standard `View` props. -## Known Issues +### Methods -- `flex:1` does not work for child views, please use `width: '100%', height: '100%'` [instead](https://github.com/callstack/react-native-pager-view/issues/186#issuecomment-675320732) +| Method | Description | Platform | +| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | :------: | +| `setPage(index: number)` | Scrolls to the given page with an animation. An invalid index is ignored. | both | +| `setPageWithoutAnimation(index: number)` | Jumps to the given page without an animation. An invalid index is ignored. | both | +| `setScrollEnabled(scrollEnabled: boolean)` | Enables or disables swiping imperatively. Prefer the `scrollEnabled` prop; use this when a re-render would get in the way, for example during an animation. | both | -- [iOS]: In case of `UIViewControllerHierarchyInconsistency` error, please use below fix: +### Types -``` -requestAnimationFrame(() => refPagerView.current?.setPage(index)); -``` +The package exports these TypeScript types: `PagerViewProps`, `PagerViewOnPageScrollEvent`, `PagerViewOnPageSelectedEvent`, `PageScrollStateChangedNativeEvent`, and their `*EventData` payloads. -## Preview +## `usePagerView` hook -### Android +`usePagerView` bundles the state and handlers you usually wire up yourself: the ref, the active page, the scroll state, the scroll progress, and helpers to add or remove pages and to toggle scrolling, animation and overdrag. It also returns `AnimatedPagerView`, which is `PagerView` wrapped with `Animated.createAnimatedComponent`. -| horizontal | vertical | -| :---------------------------------------------------------------: | :------------------------------------------------------------------------: | -| ViewPager | ViewPager | +```tsx +import { View, Text } from 'react-native'; +import { usePagerView } from 'react-native-pager-view'; -### iOS +export function PagerHookExample() { + const { AnimatedPagerView, ref, ...rest } = usePagerView({ pagesAmount: 10 }); -| horizontal | vertical | -| :------------------------------------------------------------------: | :--------------------------------------------------------------------: | -| ViewPager | ViewPager | + return ( + + {rest.pages.map((page) => ( + + {`Page ${page}`} + + ))} + + ); +} +``` + +The returned object also includes `activePage`, `progress`, `scrollState`, `setPage`, `addPage`, `removePage`, `toggleScroll`, `toggleAnimation` and `toggleOverdrag`. See the [full example](example/src/PagerHookExample.tsx). -## Reanimated onPageScroll handler +## Reanimated `onPageScroll` handler -An example can be found [here](https://github.com/callstack/react-native-pager-view/blob/master/example/src/ReanimatedOnPageScrollExample.tsx) +To handle `onPageScroll` on the UI thread with [Reanimated](https://docs.swmansion.com/react-native-reanimated/), build an event handler with `useEvent` and pass it to an animated `PagerView`: -#### Instructions +```tsx +import PagerView from 'react-native-pager-view'; +import Animated, { useEvent, useHandler } from 'react-native-reanimated'; -To attach reanimated handler with `onPageScroll` follow the below steps. +const AnimatedPagerView = Animated.createAnimatedComponent(PagerView); -```jsx -// 1. Define the handler function usePageScrollHandler(handlers, dependencies) { const { context, doDependenciesDiffer } = useHandler(handlers, dependencies); - const subscribeForEvents = ['onPageScroll']; return useEvent( (event) => { @@ -216,90 +171,48 @@ function usePageScrollHandler(handlers, dependencies) { onPageScroll(event, context); } }, - subscribeForEvents, + ['onPageScroll'], 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); - }, -}); +function MyPager() { + const handler = usePageScrollHandler({ + onPageScroll: (e) => { + 'worklet'; + console.log(e.offset, e.position); + }, + }); -; + return ; +} ``` -## usePagerView Hook Usage -The `usePagerView` hook is a convenient way to manage the state and control the behavior of the `` component. It provides functions and variables to interact with the pager, such as navigating between pages and enabling/disabling scrolling. +See the [full example](example/src/ReanimatedOnPageScrollExample.tsx). -Below is an example of how to use the usePager hook: +## Preview -```jsx -export function PagerHookExample() { - const { AnimatedPagerView, ref, ...rest } = usePagerView({ pagesAmount: 10 }); - - return ( - - - {useMemo( - () => - rest.pages.map((_, index) => ( - - - - {`page number ${index}`} - - - )), - [rest.pages] - )} - - - - ); -} -``` -### How the Example Works: +### Android + +| horizontal | vertical | +| :---------------------------------------------------------------: | :------------------------------------------------------------------------: | +| ViewPager | ViewPager | -- **Pager View Setup**: The `AnimatedPagerView` component wraps `PagerView` in React Native's animation capabilities. It accepts multiple props from the `usePager` hook, such as `overdragEnabled`, `scrollEnabled`, `onPageScroll`, `onPageSelected`, and others to manage pager behavior. +### iOS -- **Rendering Pages**: The pages are dynamically generated using the `rest.pages` array (initialized by `usePager`). The `useMemo` hook ensures the pages are only recomputed when necessary for performance reasons. +| horizontal | vertical | +| :------------------------------------------------------------------: | :--------------------------------------------------------------------: | +| ViewPager | ViewPager | -### Conclusion +## Migration -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. +- **8.x → 9.x**: the Android implementation moved from `ViewPager2` to Jetpack Compose. The JavaScript API did not change. +- **7.x → 8.x**: the iOS implementation moved from `UIPageViewController` to SwiftUI. The JavaScript API did not change. +- **6.x → 7.x**: only the New Architecture is supported. Enable it in your app before upgrading. +## Contributing + +See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. ## License diff --git a/example/src/utils.ts b/example/src/utils.ts index 44e0d6a2..490ad02b 100644 --- a/example/src/utils.ts +++ b/example/src/utils.ts @@ -13,7 +13,7 @@ export const IMAGE_URIS = [ // Unicodes issue on iOS 26.3 https://github.com/facebook/react-native/issues/56183 export const thumbsUp = '\uD83D\uDC4D'; export const logoUrl = - 'https://raw.githubusercontent.com/callstack/react-native-pager-view/master/img/viewpager-logo.png'; + 'https://raw.githubusercontent.com/callstack/react-native-pager-view/main/img/viewpager-logo.png'; export type CreatePage = { key: number;