How to pass params to tab navigator React navigation 5?

Estimated read time 2 min read

To pass parameters to a screen in a tab navigator with React Navigation 5, you can use the initialParams prop on the Screen component.

Here’s an example of how to pass parameters to a screen in a tab navigator:

import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Screen1 from './Screen1';
import Screen2 from './Screen2';

const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen
        name="Screen1"
        component={Screen1}
        initialParams={{ name: 'John' }}
      />
      <Tab.Screen name="Screen2" component={Screen2} />
    </Tab.Navigator>
  );
}

export default MyTabs;

In this example, we’re defining a Tab navigator with two screens: Screen1 and Screen2. We’re passing a name parameter to Screen1 using the initialParams prop on the Screen component.

To access the parameter in the Screen1 component, we can use the route.params object. Here’s an example of how to do it:

import React from 'react';
import { Text } from 'react-native';

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

  return <Text>Hello, {name}!</Text>;
}

export default Screen1;

In this example, we’re using destructuring to extract the name property from the route.params object.

Note that the initialParams prop sets the initial parameters for a screen, but you can also update the parameters dynamically using the setParams method on the navigation object. For example:

import React from 'react';
import { Button, Text } from 'react-native';

function Screen2({ navigation, route }) {
  const { name } = route.params;

  function handlePress() {
    navigation.setParams({ name: 'Jane' });
  }

  return (
    <>
      <Text>Hello, {name}!</Text>
      <Button title="Change Name" onPress={handlePress} />
    </>
  );
}

export default Screen2;

In this example, we’re using the setParams method on the navigation object to update the name parameter dynamically when the user presses the “Change Name” button.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply