In React Navigation with TypeScript, you can define initialProps on the parent component of a nested navigation using the useRoute hook and the initialParams option in the navigator's screen configuration. This allows you to pass initial props from the parent component down to the child screens of the nested navigator.

Here's an example of how you can achieve this:

  1. Define your nested navigator with initialParams in its screen configuration:
tsx
// ChildNavigator.tsx import { createStackNavigator } from '@react-navigation/stack'; import ChildScreen1 from './ChildScreen1'; import ChildScreen2 from './ChildScreen2'; const Stack = createStackNavigator(); const ChildNavigator = () => { return ( <Stack.Navigator initialRouteName="ChildScreen1"> <Stack.Screen name="ChildScreen1" component={ChildScreen1} /> <Stack.Screen name="ChildScreen2" component={ChildScreen2} /> </Stack.Navigator> ); }; export default ChildNavigator;
  1. In the parent component, define the initialProps and pass them to the nested navigator using the initialParams option:
tsx
// ParentComponent.tsx import React from 'react'; import { View, Text, Button } from 'react-native'; import { NavigationContainer, useRoute } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import ChildNavigator from './ChildNavigator'; const Stack = createStackNavigator(); const ParentComponent = () => { const initialProps = { foo: 'bar', someValue: 42 }; return ( <Stack.Navigator> <Stack.Screen name="ParentScreen" component={ParentScreen} initialParams={initialProps} /> <Stack.Screen name="ChildNavigator" component={ChildNavigator} /> </Stack.Navigator> ); }; const ParentScreen = () => { const route = useRoute(); const { foo, someValue } = route.params; // Access the initialProps here return ( <View> <Text>Parent Screen</Text> <Text>foo: {foo}</Text> <Text>someValue: {someValue}</Text> <Button title="Go to Child Screen 1" onPress={() => { // Navigating to the first screen in the ChildNavigator // You can pass additional params to the child screen if needed navigation.navigate('ChildNavigator', { additionalParam: 'Hello' }); }} /> </View> ); }; export default ParentComponent;

In this example, the ParentComponent sets the initialProps object, which is passed to the ParentScreen through the initialParams option. The useRoute hook is then used to access these initial props in the ParentScreen, and you can pass them down further to any of the child screens within the ChildNavigator.

Remember that when using TypeScript, you might need to define appropriate types for the props passed to screens and components to ensure type safety.

Have questions or queries?
Get in Touch