Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define React Navigation navigationOptions parameter in Typescript

In a React Native app using React Navigation, I have a screen component, where I want to define the title using the navigationOptions property based on the given parameters, like this:

static navigationOptions = ({navigation}) => ({
    title: navigation.state.params.myParam
});

It works fine, and the title is printed correctly.
However, now I'm migrating the app to Typescript, and I want to define myParam as a required string, and I don't know how to define the parameter so I get autocompletion in my IDE:

({navigation}: /* WhatDoIPutHere? */)

I tried the approach in this Gist, but as I commented myself in there, that's not working fine for me...

What's the correct type I can use to define the expected parameters there?

like image 953
MikO Avatar asked May 14 '18 14:05

MikO


People also ask

What type is navigation in react native?

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.

What is react-native-screens?

react-native-screens provides native primitives to represent screens instead of plain <View> components in order to better take advantage of operating system behavior and optimizations around screens. This capability is used by library authors and unlikely to be used directly by most app developers.

How do you use navigate in react?

useNavigation is a hook which gives access to navigation object. It's useful when you cannot pass the navigation prop into the component directly, or don't want to pass it in case of a deeply nested child. useNavigation() returns the navigation prop of the screen it's inside.


1 Answers

Actually the solution in the Gist I linked from the question is almost correct - the problem is just navigation.state.params might be undefined according to the definition! So, Typescript and my IDE (smart guys) were complaining about it...

You can see the relevant bit from the definitions here:

export interface NavigationLeafRoute<Params> {
  // ...
  /**
   * Params passed to this route when navigating to it,
   * e.g. `{ car_id: 123 }` in a route that displays a car.
   */
  params?: Params;
}

So I ended up doing this in my component:

interface Params {
    myParam: string
}

// ...

static navigationOptions = ({navigation}: NavigationScreenProps<Params>) => ({
    title: navigation.state.params ? navigation.state.params.myParam : 'Default title'
});

And it works nicely, including autocompletion in my IDE - starting to like Typescript a lot!

like image 66
MikO Avatar answered Nov 14 '22 03:11

MikO