how to use navigation.replace in TypeScript?

Viewed 3876

I am trying to use this in my code:

const navigation = useNavigation();
navigation.replace('AllFriends')

But I keep getting an error that:

Property 'replace' does not exist on type 'NavigationProp<Record<string, object | undefined>, string, NavigationState, {}, {}>'.

I also tried using this

const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()
navigation.replace('route');

as suggested here: https://github.com/react-navigation/react-navigation/issues/8256

but this gives me an error on replace that expected 2 arguments but got only 1...

I am using "@react-navigation/native": "^5.5.1",

3 Answers

The replace method is only available to screens within StackNavigators. We need a way to explicitly type that the screen is such.

When you instantiate your StackNavigator, you have the ability to pass in a type that defines your Routes with the parameters they expect to receive:

export type StackParams = {
   MyRoute: undefined;
   AnotherRoute: {
      id: number
   }
}

createStackNavigator<StackParams>();

Then in the screen you pass that param list to StackNavigationProp

import { StackNavigationProp } from '@react-navigation/stack/';
import { StackParams} form 'your/routes';

const navigation =  useNavigation<StackNavigationProp<StackParams>>()
navigation.replace('route');

Doing this affirms that this is a Stack screen and provides a list of routes that you can navigate to:

replace('AnotherRoute') //success!
replace('FakeRoute') //error, this was not defined in our RouteParams
const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()
navigation.replace('route');
Related