Access parent stack navigator's navigation object from nested child screen

Viewed 1369

I am using React Navigation v5 in my react-native project.

I have a nested stack navigator.

The parent stack navigator MyParentFlow which has a screen component which hosts another stack navigator:

const MyParentFlow = ({route, navigation}) => {

   const MyStack = createStackNavigator();

  return (
    <MyStack.Navigator
       initialRouteName={...}
       ...>
       {/*HERE is the nested children stack navigator*/}
       <MyStack.Screen
         name={FLOWS.MyChildrenFlow}
         component={MyChildrenFlow}
       />
       <MyStack.Screen .../>
       ...
    </MyStack.Navigator>
)
}

My nested stack navigator MyChildrenFlow:

const MyChildrenFlow = ({route, navigation}) => {

   const MyStack = createStackNavigator();


  return (
    <MyStack.Navigator
       initialRouteName={...}
       ...>
       {/*HERE is a child screen in the nested navigator*/}
       <MyStack.Screen 
         name="MyChildScreen"
         component={MyChildScreen}
       />
       <MyStack.Screen .../>
       ...
    </MyStack.Navigator>
)
}

In the child screen hosted by the nested stack navigator:

const MyChildScreen =({navigation})=> {
    /* I need to set options for the header of the parent's navigation */
    navigation.setOptions({
    headerRight: () => (
      ...
      />
    ),
  });

}

In the child screen hosted by the nested stack navigator, I need to set header via navigation for the parent navigator. My above code doesn't work because that navigation object is the nested stack navigator's , not the parent's.

My question is how can I get access of parent's navigator in the nested child screen and set the navigation options for it?

2 Answers

Try this

navigation.getParent().dispatch(
                    CommonActions.navigate({
                            name: 'screenName',
                            params: {},
                        }
                    ))
Related