Faire
Faire

Reputation: 1011

How should I define type of props supplied by react-navigation?

I have a react native app with navigation stack defined:

 <Stack.Navigator
            initialRouteName={NavigationLocations.SIGNUP}
            ...
            }}>
           ...
            <Stack.Screen
                name={NavigationLocations.SHEET}
                component={Sheet}
                options={
                    {
                        title: "Character sheet",
                        headerLeft: null
                    }}
            />
        </Stack.Navigator>

This is my navigation props definition:

export type RootStackParamList = {
    Signup: undefined,
    Login: undefined,
    Dashboard: undefined,
    SheetView: {sheet: ISheet}
};

How should I define the sheet props in the component that is receiving the sheet object passed by the navigation?

type Props = StackScreenProps<RootStackParamList, NavigationLocations.SHEET>

export default function Sheet({sheet}: Props) {
    const sheet = props.route.params.sheet;

Currently I am getting this error: Error:(11, 32) TS2339: Property 'sheet' does not exist on type 'StackScreenProps<RootStackParamList, NavigationLocations.SHEET>'.

I am using the NavigationLocations enum because I generally dislike using strings as identifiers, but I think that my implementation has introduced an error here. What am I doing wrong?

Upvotes: 0

Views: 542

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42228

The StackScreenProps just includes the types for the props navigation and route.

type Props = {
    navigation: StackNavigationProp<RootStackParamList, NavigationLocations.SHEET>;
    route: Route<NavigationLocations.SHEET, {
        ...;
    }>;
}

It looks like you've tried to access sheet as a top-level prop:

function Sheet({sheet}: Props) {

And also as a nested property:

const sheet = props.route.params.sheet;

That second one is correct. We can take off some of the levels of nesting if we do this:

export default function Sheet({ navigation, route }: Props) {
  // sheet has type ISheet
  const {sheet} = route.params;

The enum should not be a problem as long as the value of the enum matches the key in the RootStackParamList. I get a different error when it doesn't match, so that's not your issue.

Upvotes: 1

Related Questions