React Navigation route.params typescript

Viewed 18321

I'm creating a Expo managed React Native app with TypeScript and having some problems with React Navigation and TypeScript.

I want to specify the icon for the Bottom Tab Navigator on the Tab.Screen component.

This code works but complains because route.params could be undefined (line 10).

Property 'icon' does not exist on type 'object'

Can I make the icon prop required on initialParams?

I have looked in the documentation without any luck.

const App: React.FC<{}> = () => {
  return (
    <SafeAreaView style={styles.container}>
      <NavigationContainer>
        <Tab.Navigator
          screenOptions={({ route }) => ({
            tabBarIcon: ({ size, color }) => (
              <MaterialIcons
                size={size}
/* ===> */      name={route.params.icon}
                color={color}
              />
            ),
          })}
        >
          <Tab.Screen
            name="EventListView"
            initialParams={{ icon: 'view-agenda' }}
            component={EventListScreen}
          />
          <Tab.Screen
            name="CreateEvent"
            initialParams={{ icon: 'public' }}
            component={SettingsScreen}
          />
        </Tab.Navigator>
      </NavigationContainer>
    </SafeAreaView>
  )
}
3 Answers

import { RouteProp } from '@react-navigation/native';

  route: RouteProp<{ params: { icon: ICON_TYPE } }, 'params'>

I recently had the same issue, I came up with this, it seems to be working fine.

The right way of doing this would be to define a type with the params, and send that as the type argument when creating the navigator. Something like this:

type TabNavigatorParamList = {
  EventListView: { icon: string }
  CreateEvent: { icon: string }
}

const Tab = createBottomTabNavigator<TabNavigatorParamList>(); //*

* I've assumed your Tab component was a BottomTabNavigator, but the same code would work no matter what kind of create{whatever}Navigator you use.

Just like that your Tab.Navigator and Tab.Screen will have the right type for their route prop.

There's more info in the docs, and more advanced situations like annotating hooks and nested navigators.

I think you can just use this syntax:

name={route.params?.icon}

Otherwise use this:

name={route.params?.icon ?? 'defaultName'}

According to the documentation this syntax guards against params being undefined in some cases and provides a default value if the params.someParam is undefined or null.

For more information read here: https://reactnavigation.org/docs/upgrading-from-4.x/#no-more-getparam.

Related