Add strong typing for react navigation props
Just add NavigationType to your Props, like this:
import { StackNavigator, NavigationScreenProp } from 'react-navigation';
export interface HomeScreenProps {
navigation: NavigationScreenProp<any,any>
};
export class HomeScreen extends React.Component<HomeScreenProps, object> {
render() {
return (
<View style={styles.container}>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}
if you are passing the navigation
prop that is defined by
let navigation = useNavigation()
to a component, the best way of typing is:
import {NavigationProp, ParamListBase} from '@react-navigation/native';
navigation: NavigationProp<ParamListBase>
Update:
Here is a better approach for strong navigation typing, using the latest @react-navigation
version (6.x
)
full example:
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
type RootStackParamList = {
Pdp: undefined; //current screen
PdpComments: {slug: string}; // a screen that we are
// navigating to, in the current screen,
// that we should pass a prop named `slug` to it
Sellers: {data: Array<string>};
Favorites: undefined; // a screen that we are navigating to
// in the current screen, that we don't pass any props to it
};
interface IPdpPageProps {
navigation: NativeStackNavigationProp<RootStackParamList, 'Pdp'>;
}
// Since our screen is in the stack, we don't need to
// use `useNavigation()` to provide the `navigation` to
// our component, we just need to read it as a prop
function Pdp({navigation}: IPdpPageProps) {
return ...
}
A minimal configuration, with version 6.x
import { NavigationProp } from "@react-navigation/native";
interface RouterProps {
navigation: NavigationProp<any, any>;
}
<TouchableOpacity onPress={() => navigation.navigate('Home')}>
<Text>Navigate to Home</Text>
</TouchableOpacity>