Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typescript with useRoute on react navigation v5

Tags:

I am trying to extract the params as follows using useRoute as follows.

  const route = useRoute();
  const { params } = route;
  const {
   id, name,
  } = params;

Everything works fine but the linter is highlighting id and namewith the following error.

Property 'id' does not exist on type 'object | undefined

How do I overcome this issue.

like image 432
Muljayan Avatar asked Apr 15 '20 11:04

Muljayan


People also ask

Is it good to use TypeScript with React Native?

With all these advantages and disadvantages, Typescript still provides great value to your project. You will save many hours of debugging time by using TypeScript. Therefore, you should definitely use TypeScript in your React Native Project.

Can you mix TypeScript and Javascript React Native?

While React Native is built in Flow, it supports both TypeScript and Flow by default.


1 Answers

react-navigation exports a couple utility types to make your life easier when using hooks and defining props for your own components. They depend on you first defining types for your navigators.


Lets say you have a stack with two screens, A and B. First define what params each of those takes:

type StackParamsList = {
  A: undefined;
  B: {
    id: string;
    name: string;
  };
}

For typing useRoute in your screen B:

import { RouteProp } from '@react-navigation/native';

const route = useRoute<RouteProp<StackParamsList, 'B'>>();

route.params.id // OK
route.params.foo // error

Check the Type checking with Typescript article in react-navigation docs for more details and examples of typing other elements of your navigation stack.

like image 85
Marek Lisik Avatar answered Oct 02 '22 13:10

Marek Lisik