Search code examples
reactjsreact-nativereact-navigationreact-navigation-v5

react navigation type for typescript in component screen props


I have a warning or error for navigation props in component screen

export default function FoodMenuList({ navigation }) {}

because I dont assign type for navigation

Binding element 'navigation' implicitly has an 'any'

I tried to search navigation props type for react navigation, but I dont find

what is react-navigation navigation props type?

or may be?

export default function FoodMenuList({ navigation }: {navigation: {navigate:Function}}) {}

or may be there is better solution?


Solution

  • According to the documentation provided by react-navigation https://reactnavigation.org/docs/typescript/#type-checking-screens

    To type check our screens, we need to annotate the navigation prop and the route prop received by a screen. The navigator packages in React Navigation export a generic types to define types for both the navigation and route props from the corresponding navigator.

    For example, you can use NativeStackScreenProps for the Native Stack Navigator.

    import type { NativeStackScreenProps } from '@react-navigation/native-stack';
    
    type RootStackParamList = {
      Home: undefined;
      Profile: { userId: string };
      Feed: { sort: 'latest' | 'top' } | undefined;
    };
    
    type Props = NativeStackScreenProps<RootStackParamList, 'Profile'>;
    

    This allows us to type check route names and params which you're navigating using navigate, push etc. The name of the current route is necessary to type check the params in route.params and when you call setParams.

    Then you can use the Props type you defined above to annotate your component.

    For function components:

    function ProfileScreen({ route, navigation }: Props) {
      // ...
    }