When I use useNavigation or from props { navigation } for navigate between screen using navigation.navigate('Home') the typescript return error Argument of type '"Main"' is not assignable to parameter of type '{ key: string; params?: undefined; merge?: boolean | undefined; } | { name: never; key?: string | undefined; params: never; merge?: boolean | undefined; }' what does it mean?
below is my code:
import React from 'react';
import { View } from 'react-native';
import { Button } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';
const Home: React.FC = () => {
const navigation = useNavigation();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button onPress={() => navigation.navigate('Main')}>Navigate</Button>
</View>
);
};
export default React.memo(Home);
previously i used react navigation v5 and working find with that method
thanks for your help
Maybe you want to do something like this:
export type RootStackParamList = {
Main: undefined;
Home: undefined;
};
const Stack = createStackNavigator<RootStackParamList>();
export const RootNavigator = () => {
return (
<Stack.Navigator initialRouteName="Main">
<Stack.Screen
name="Main"
component={Main}
/>
<Stack.Screen
name="Home"
component={Home}
/>
</Stack.Navigator>
);
};
then in your code to do something like this:
type homeScreenProp = StackNavigationProp<RootStackParamList, 'Home'>;
const Home: React.FC = () => {
const navigation = useNavigation<homeScreenProp>();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button onPress={() => navigation.navigate('Main')}>Navigate</Button>
</View>
);
};
This is because you must specify this type, as this will ensure type-safety.
Solution:
1 - Type checking the navigator
// root.routes.tsx
import { createStackNavigator } from '@react-navigation/stack';
export type RootStackParamList = {
Home: undefined;
Profile: { userId: string };
Feed: { sort: 'latest' | 'top' } | undefined;
};
const RootStack = createStackNavigator<RootStackParamList>();
2 - Specify a global type for your root navigator
// navigation.d.ts
import { RootStackParamList } from '../routes/root.routes';
declare global {
namespace ReactNavigation {
interface RootParamList extends RootStackParamList {}
}
}
3 - Use it!
import { useNavigation } from '@react-navigation/native';
const navigation = useNavigation();
navigation.navigate('Home');
Refs:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With