Reputation: 1780
I'm migrating from react-navigation v5
to v6
I'm trying to add type checking and I encouraged a problem that couldn't find a solution from the docs
import { StackScreenProps } from '@react-navigation/stack';
export type RootStackParamList = {
Home: StackScreenProps<HomeStackParamList>;
Users: StackScreenProps<UsersStackParamList>;
//other stacks that I have
};
export type HomeStackParamList = {
Home: undefined;
Bets: { id: string };
}
export type UsersStackParamList = {
Profile: undefined;
ProfileCreate: undefined;
};
//get global type safety I'm using this as recommended in docs
declare global {
namespace ReactNavigation {
interface RootParamList extends RootStackParamList {}
}
}
The problem arises when I try to use the useNavigation()
hook
let's say I want to navigate from the Home
Component to the Users ProfilCreate
as below
import { useNavigation } from '@react-navigation/native';
const navigation = useNavigation();
//as I understood it should work like this
navigation.navigate('Users',{screen:'ProfileCreate'})
But the problem is I can't use {screen:'ProfileCreate'}
here it allows me to pass this object.
Even if i use the navigate as below with the intialRouteName
navigation.navigate('Users');
Argument of type 'string' is not assignable to parameter of type '{ key: string; params?: StackScreenProps | undefined; merge?: boolean | undefined; } | { name: "Users"; key?: string | undefined; params: StackScreenProps<...>; merge?: boolean | undefined; } | ... 7 more ... | { ...; }'.
Please note that I'm using the Stack
navigation, not the NativeStack
navigation.
I have another question. Suppose we have a stack with routes(ex:SomeStackParamList
) that do not contain any parameters. Even if there are no parameters, do we still need to add them to the RootStackParamList to receive type suggestions at the global level?
export type SomeStackParamList = {
OneRote: undefined;
TwoRoute: undefined;
}
Upvotes: 0
Views: 85
Reputation: 10152
Your types are incorrect. StackScreenProps
shouldn't be used like that. You need to use NavigatorScreenParams
:
export type RootStackParamList = {
Home: NavigatorScreenParams<HomeStackParamList>;
Users: NavigatorScreenParams<UsersStackParamList>;
//other stacks that I have
};
Please follow the docs for TypeScript setup https://reactnavigation.org/docs/typescript/#nesting-navigators
Upvotes: 0