31

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;
kboul
  • 13,836
  • 5
  • 42
  • 53
Christian Prado
  • 313
  • 1
  • 3
  • 5

3 Answers3

77

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

Paduado
  • 1,281
  • 12
  • 5
  • I was getting a similar issue, but `params` did not exist. I had to add `| undefined` basically to the Detail portion of the type definition – Ray Jan 31 '23 at 22:19
14

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>
}
0

This is too complicated. There is an easier way to set initialParams in TS.

Set up:

type StackParamList = {
  TheSource: { endpoint: string; type: string;};
  BenefitDetail: React.FC;
  ItineraryMain: {reFetch: boolean;};
  Today: React.FC;
};

const Stack = createStackNavigator<StackParamList>();

Then when using it:

const TheSourceRoute = (): React.ReactElement => {
  return (<StackNavigator id="TheSource" element={
    <Stack.Screen name="TheSource" component={WebviewModal} initialParams={{ endpoint: sourceUrl, type: 'directsource' }}
      options={{
        title: 'The Source',
      }}/>
  }/>
  );
};