Search code examples
javascriptreact-nativenavigationreact-navigation

React Navigation - Listen parent action in child component


I have a tab navigator Screen in which there are 2 tabs. The parent Stack has button in the header, which should work differntly w.r.t Two different screens/Tabs.

enter image description here

Now, What I have done is -

navigation.setOptions({
  headerRight: () => (
    <TouchableOpacity>
      <Text>Update</Text>
    </TouchableOpacity>
  ),
});

How I can handle the click of Save button from both the components under Tabs Navigator?

Note - I am using react-navigation@v6


Solution

  • Here, I want to give the answer of my question myself.

    The solution is to not set the Navigation right button from Parent navigator, Access the parent navigation from each Tab screen and set the Right header.

    Also you should use useFocusEffect to add this because it can be different for different tabs of the navigator. Here's how you can do it -

    import { useFocusEffect } from '@react-navigation/native';
    
    useFocusEffect(() => {
        navigation.getParent().setOptions({
          headerRight: () => (
            <TouchableOpacity 
              disabled={true}
              style={styles.headerRight}>
              <Text style={{ color: 'black' }}>Save</Text>
            </TouchableOpacity>
          ),
        });
    });