React Navigation Documentation

repository·main·Indexed 43 days ago

https://github.com/react-navigation/react-navigation.github.io

Documentation for React Navigation, including guides on Stack, Drawer, and Tab navigators. Covers version 2.0 and 3.0 release candidates, featuring the Contextual Navigation Actions API, shallow navigation options, and web support via @react-navigation/web.

Tokens
35K
Snippets
103
Records
140
Agent score
55%

What's inside React Navigation

  1. Overview of React Navigation 7.0 features

    main

    React Navigation 7 introduces several major improvements and new APIs designed to enhance developer experience and performance:

    • Static API: An optional API that simplifies navigator configuration and improves TypeScript support and deep linking.
    • Preloading Screens: Support for preloading screens in many navigators to improve perceived performance.
    • Layout Props: New layout props for navigators and screens to add UI and behavior.
    • Web Integration: Improved web support with anchor tag rendering and revamped Link and useLinkProps APIs that use screen names instead of paths.
    • Header Searchbar: All navigators with a header now support a searchbar via the headerSearchBarOptions option.
    • useLogger Devtool: A new useLogger hook for debugging navigation actions and state in the console (replacing the Flipper plugin).
    • Bottom Tab Navigator Enhancements: Supports sidebar positioning via tabBarPosition ('left' or 'right') and custom animations via the animation option.
    • Standalone Drawer Layout: The drawer implementation used in @react-navigation/drawer is now available as the standalone package react-native-drawer-layout.
  2. New features in React Navigation 8.0 Alpha

    main

    The 8.0 alpha release introduces several significant improvements and new capabilities:

    • Native Bottom Tabs by default: Improved performance and platform integration for tab navigation.
    • Enhanced Parent Access: Ability to access route, navigation, and state for any parent screen.
    • Improved TypeScript Support: Better types specifically for static configuration.
    • History Management: Ability to push history entries without pushing new screens.
    • Theming Enhancements: Support for PlatformColor, DynamicColorIOS, and CSS custom properties within the theme.
    • Deep Linking: Support for deep linking directly to screens that are behind conditional rendering logic.
    • State Persistence: A new Persistor for maintaining navigation state across sessions.
  3. Key changes in React Navigation 6.0

    main

    React Navigation 6.0 maintains the same API as version 5 but introduces several breaking changes and refinements for consistency and flexibility:

    • Params Behavior: Navigation parameters are now overwritten by default instead of merged (though an option to merge remains available).
    • Stack Modals: On iOS, modals in the Stack Navigator use the presentation style by default. Android now includes a new slide animation for modals.
    • Drawer Animation: The Drawer Navigator now uses a slide animation by default on iOS.
    • Default Headers: Headers are now shown by default in Drawer and Bottom Tab screens, reducing the need for nested Stack Navigators.
    • Configuration Pattern: Legacy configuration props like tabBarOptions and drawerContentOptions have been removed. These are now configured via the options prop on individual screens.
    • Material Top Tabs: Now uses a ViewPager based implementation for a more native experience.
    • UI Elements: A new UI elements library is available containing components used within React Navigation.
  4. React Navigation 8.0 Alpha Highlights

    main

    React Navigation 8.0 Alpha introduces several significant improvements and new features focused on performance, developer experience, and platform integration. Key highlights include:

    • Native Bottom Tabs by default: Improved performance and platform consistency.
    • Enhanced Parent Access: Direct access to route, navigation, and state for any parent screen.
    • Improved TypeScript Support: Better types for static configuration.
    • History Management: Ability to push history entries without pushing new screens.
    • Theming Improvements: Support for PlatformColor, DynamicColorIOS, and CSS custom properties within the theme.
    • Deep Linking: Support for deep linking to screens that are behind conditional rendering.
    • State Persistence: A new Persistor for managing state persistence.
  5. Use the Group component to organize screens and share options

    main

    The Group component allows you to organize screens within a navigator and apply shared screenOptions to all screens within that group.

    • Functionality: It is a lightweight component that does not render anything (similar to a Fragment) and does not impact performance.
    • Nesting: You can nest Group components inside other Group components.
    • Overriding: Options set on a Group can be overridden by passing specific options to individual Screen components.
    function App() {
      return (
        <Stack.Navigator>
          <Stack.Group>
            <Stack.Screen name="Home" component={HomeScreen} />
            <Stack.Screen name="Details" component={DetailsScreen} />
          </Stack.Group>
          <Stack.Group screenOptions={{ presentation: 'modal' }}>
            <Stack.Screen name="CreatePost" component={CreatePostScreen} />
          </Stack.Group>
        </Stack.Navigator>
      );
    }
  6. How navigation options resolution works (Shallow Navigation)

    main

    React Navigation 2.0 implements shallow navigation options.

    Previously, navigators would crawl into child navigators to pull navigationOptions from the deepest active screen. This often caused unexpected side effects, such as a parent stack's header title changing when a screen inside a child drawer was changed.

    Current Behavior: Navigators now only look at their direct children for navigationOptions. This prevents parent navigators from being affected by the configuration of deeply nested screens.

  7. Understand Native Navigation defaults in React Navigation 6

    main

    React Navigation 6 prioritizes native primitives for better performance and feature parity with platform defaults:

    • Stack Navigation: @react-navigation/native-stack is now the default choice. It uses UINavigationController on iOS and Fragments on Android. It is maintained alongside @react-navigation/stack for compatibility.
    • Top Tabs: @react-navigation/material-top-tabs uses react-native-pager-view by default.

    Note: @react-navigation/native-stack does not replace @react-navigation/stack; both remain valid options for your projects.

  8. Automatic TypeScript type inference for navigation hooks

    main

    React Navigation 8.0 improves TypeScript ergonomics by automatically inferring types based on the provided screen name in hooks. This reduces the need for manual type annotations.

    • useNavigation('ScreenName'): Correctly typed as StackNavigationProp<ParamList, 'ScreenName'> (or appropriate navigator type).
    • useRoute('ScreenName'): Correctly typed as RouteProp<ParamList, 'ScreenName'>.
    • useNavigationState('ScreenName', selector): Correctly typed as the specific NavigationState for the containing navigator.

    When no screen name is provided to useRoute, it returns a union of all route types in the project, maintaining type safety for reusable components.

    // navigation is correctly typed as StackNavigationProp<RootStackParamList, 'Profile'>
    const navigation = useNavigation('Profile');
    
    // route is correctly typed as RouteProp<RootStackParamList, 'Profile'>
    const route = useRoute('Profile');
    
    // state is correctly typed as StackNavigationState<RootStackParamList>
    const focusedRoute = useNavigationState(
      'Profile',
      (state) => state.routes[state.index]
    );
  9. Understand the difference between navigate() and push() in StackNavigator

    main

    In React Navigation 2.0, navigate(routeName) is "less pushy" than in 1.x.

    • navigate(routeName): Instead of always pushing a new route, it first attempts to find an existing instance of the route in the stack. If found, it jumps to that instance; otherwise, it pushes the route.
    • push(routeName): Continues to push a new route onto the stack every time it is called.

    How to update: If you require a new route to be pushed every time (the 1.x behavior), switch from navigate to push. Alternatively, you can use a unique key to ensure a new route is created:

    navigate({
      routeName: 'MyRoute',
      key: data.uniqueId,
      params: data
    });
    navigate({
      routeName: 'MyRoute',
      key: data.uniqueId,
      params: data
    });
  10. Understand updated `getId` behavior in stack navigators

    main

    In React Navigation 8, the ID returned by getId behaves more like a route name. It matches routes by ID without rearranging the stack.

    New Behavior:

    • If you are already on a screen with the same ID, it updates its params without pushing a new screen.
    • If you are on a different screen, it pushes the new screen onto the stack.
    • If you navigate to a route with an existing ID and use pop: true, it pops back to the matching route instead of moving it to the top.

    This change was made to resolve broken behavior in the Native Stack Navigator.

  11. Understand the new `navigate` behavior in StackNavigator

    main

    In React Navigation 2.0, navigate(routeName) is "less pushy" than in 1.x. Instead of always pushing a new route onto the stack, navigate will first attempt to find an existing instance of the route and jump to it.

    How to adapt:

    • If you want to ensure a new route is pushed every time, use push(routeName) instead.
    • Alternatively, use a unique key to force a new instance: navigate({ routeName: 'MyRoute', key: data.uniqueId, params: data }).