How to pass parameters to nested navigators with React native?

Estimated read time 2 min read

To pass parameters to nested navigators with React Native, you can use the route.params object in your screen components to access the parameters passed down from the parent navigator.

Here’s an example of how to pass parameters to a nested navigator:

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

const Stack = createStackNavigator();

function ProfileScreen({ route }) {
  const { name } = route.params;

  return <Text>Profile Screen for {name}</Text>;
}

function HomeScreen() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Profile"
        component={ProfileScreen}
        initialParams={{ name: 'John' }}
      />
    </Stack.Navigator>
  );
}

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

export default App;

In this example, we’re defining a ProfileScreen component that accepts parameters through the route.params object. We’re passing a name parameter to the ProfileScreen component from the HomeScreen component using the initialParams prop on the Screen component.

To access the parameter in the ProfileScreen component, we’re using destructuring to extract the name property from the route.params object.

Note that the route.params object is only available in the screen components rendered by a navigator. If you need to pass parameters to a nested navigator itself (rather than to its screens), you can do so using the initialParams prop on the navigator component itself.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply