I'm trying to get my incident object from route.params
but I don't know how to do it to make typescript recognize this prop.
Here is the function that navigate to my Detail page passing incident to params:
const navigateToDetail = (incident: IncidentProps): void => {
navigation.navigate('Detail', { incident });
};
And Here is part of Detail page code where I try to get this object from route.params:
type IncidentRouteParams = {
incident: IncidentProps;
}
const Detail: React.FC = () => {
const navigation = useNavigation();
const route = useRoute();
const incident = route.params.incident;
I think I need to pass this IncidentRouteParams type somehow to const route = useRoute()
Thanks in advance.
Here is the image with the error:
EDIT:
I did like this, and it worked, but I don't know if it is the right way:
const route = useRoute<RouteProp<Record<string, IncidentRouteParams>, string>>();
const incident = route.params.incident;
While React Native is built in Flow, it supports both TypeScript and Flow by default.
React Navigation is the most popular navigation library in the React Native ecosystem and the best choice for most apps. It is maintained by the Expo team and supports Android, iOS, and the web. This video demonstrates using React Navigation on iOS, Android, and web.
React Navigation library is one of the most used navigation libraries in the React Native ecosystem. It is written in TypeScript, and you can create React components and apply any navigation patterns from Stack, Tab, and Drawer.
Just did this yesterday!
TLDR: First you need to define a type with each screen name and the params it receives:
type ParamList = {
Detail: {
incident: IncidentProps;
};
};
Then you use that param and the screen name in RouteProp
:
const route = useRoute<RouteProp<ParamList, 'Detail'>>();
Here are the docs explaining all this https://reactnavigation.org/docs/typescript
You can also create a type considering the ParamList you want, so you only need to import this type into your component and pass the RouteName as parameter.
import { RouteProp } from '@react-navigation/native';
export type RootStackParamList = {
Home: undefined;
Feed: { sort: 'latest' | 'top' };
};
export type RootRouteProps<RouteName extends keyof RootStackParamList> = RouteProp<
RootStackParamList,
RouteName
>;
Usage:
export const Feed = () => {
const route = useRoute<RootRouteProps<'Feed'>>();
return <Text>{route.params.sort}</Text>
}
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