Best practice to handle route names in react-navigation v5

Viewed 338

I'm new to react navtive and wondering how to handle the route names for the react-navigation v5.

I'm starting of a company internal boilerplate project with react-navigation in version 4 and updating that to version 5. So far everything runs fine.

The problem now is, the project was using a file which had all the route names defined as so:

export const HOME_ROUTE = 'Home';
export const LOGIN_ROUTE = 'Login';
export const REGISTER_ROUTE = 'Register';

That also works in react-navigation v5.

Then I wanted to eliminate the warnings on the any type of the navigation prop. The documentation states I should add the type definition. Then I ran into the first problem.

With the route constants I would have liked to do it somehow like this:

export type RootStackParamList = {
  HOME_ROUTE: undefined;
  LOGIN_ROUTE: undefined;
  REGISTER_ROUTE: undefined;
};

That does not work, as I cannot find a way to use constants in a type definition(Which makes sense).

I was thinking about removing the routeConstants altogether, but the disadvantage is that I do not have autcompletion on typing the route names, which might lead to hard to spot bugs. At least I think that might happen.

Is there a preferred way to handle this problem? I looked into a few other boilerplate projects but they all just used strings as the route names.

1 Answers

Thanks to a coworker I found the solution:

The syntax to unpack a constant is like this:

export type RootStackParamList = {
  [HOME_ROUTE]: undefined;
  [LOGIN_ROUTE]: undefined;
  [REGISTER_ROUTE]: undefined;
};
Related