What is the best way to define type for screen's navigation
prop, when screen is in different file that router? Let's say I have one file, in which I define routes:
//Router.tsx
type RootStackParamList = {
Home: undefined;
Profile: undefined;
}
const Stack = createStackNavigator<RootStackParamList>();
// Component rendering navigator
const Router = () => {
.
.
.
}
Then I have the separate file for screen:
// Home.tsx
// here has to be the same RootStackParamList
// that we've already defined in Router.tsx
type = HomeScreenNavigationProp = StackNavigationProp<
RootStackParamList,
"Home"
>;
type Props: {
navigation: HomeScreenNavigationProp
}
const Home = ({navigation}: Props) => {
.
.
.
}
Do I have to copy RootStackParamList
over and over to every screen or create something like types.ts
file and import it from there? Is there a better way to handle it? I am using navigation
almost in every component.
You can try this:
type RootStackComponent<RouteName extends keyof RootStackParamList> = React.FC<
navigation: StackNavigationProp<RootStackParamList, RouteName>,
route: RouteProp<RootStackParamList, RouteName>
>
const Home: RootStackComponent<'Home'> = ({ navigation, route }) => {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With