Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation route.params typescript

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>
  )
}
like image 742
Dainel vdM Avatar asked Sep 06 '25 09:09

Dainel vdM


2 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.

like image 187
Robert Sidzinka Avatar answered Sep 08 '25 01:09

Robert Sidzinka


It is now pretty well explained in the official doc. Working well.

Read the doc: https://reactnavigation.org/docs/typescript/#type-checking-the-navigator

Here a quick look of how it could look like:

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

type RootStackParamList = {
   Home: undefined;
   Profile: { userId: string };
   Feed: { sort: 'latest' | 'top' } | undefined;
};

const RootStack = createStackNavigator<RootStackParamList>();

<RootStack.Navigator initialRouteName="Home">
   <RootStack.Screen name="Home" component={Home} />
   <RootStack.Screen
      name="Profile"
      component={Profile}
      initialParams={{ userId: user.id }}
   />
   <RootStack.Screen name="Feed" component={Feed} />
</RootStack.Navigator>

Then to type check your component:

interface Props extends NativeStackScreenProps<RootStackParamList, 'Profile'> {
    // other props ...
}

const ProfileScreen: React.FC<Props> = ({ route, navigation }) => {
   // ...
}
like image 28
Pascal Lapointe Avatar answered Sep 08 '25 02:09

Pascal Lapointe