react-nativereact-navigationreact-navigation-v5react-navigation-bottom-tab

How to pass parameters to routes using tab navigator (createMaterialBottomTabNavigator)?


I am using createMaterialBottomTabNavigator and I want to pass parameters to the routes:

return (
   <Tab.Navigator initialRouteName="Home">
      <Tab.Screen name="Home" component={home_customers} />
      <Tab.Screen name="Favorites" component={favorite_vendors} />
      <Tab.Screen name="More" component={settings_screen} />
   </Tab.Navigator>
);

I could only find an attribute called initialParams which I am not sure if it is the right thing to use in this case. So, what I want to do is to GET parameters from the previous screen and PASS that parameter to each of these three screens!

UPDATE

ok, I found out how to GET the parameters but I still don't know how to pass those parameters to route screens!

export default function home_customers_bar({ route, navigation }) {
    const current_city_ = route.params.current_user_city_; //here I get the parameter from the previous screen
    
    return (
        <Tab.Navigator initialRouteName="Home">
            <Tab.Screen name="Home" component={home_customers} />
            <Tab.Screen name="Favorites" component={favorite_vendors} />
            <Tab.Screen name="More" component={settings_screen} />
        </Tab.Navigator>
    );
}

Solution

  • If you only need to pass the data to a limited number of screens you can set the initialParams like this:

    export default function home_customers_bar({route, navigation}) {
      const current_city_ = route.params.current_user_city_; //here I get the parameter from the previous screen
    
      return (
        <Tab.Navigator initialRouteName="Home">
          <Tab.Screen
            name="Home"
            component={home_customers}
            initialParams={{currentCity: current_city_}}
          />
          <Tab.Screen
            name="Favorites"
            component={favorite_vendors}
            initialParams={{currentCity: current_city_}}
          />
          <Tab.Screen name="More" component={settings_screen} />
        </Tab.Navigator>
      );
    }
    

    Then you can retrieve the params inside a screen component like this:

    function home_customers({ route }) {
      const currentCity = route.params.currentCity;
    
      // Do something with it...
    }
    

    If you're going to be passing this value around to a lot of different components then it's probably better to use something like react context https://reactnavigation.org/docs/upgrading-from-4.x/#global-props-with-screenprops.