How to use navigation.navigate from a component outside the stack.navigation

Carlos Saiz Orteu picture Carlos Saiz Orteu · Apr 12, 2020 · Viewed 7k times · Source

I have an application using React native where I am using react-navigation (5.2.9).

I built a Stack.Navigator where I've got my screens but I want the Footer component to be outside so it renders in all screens. The problem is, I can't navigate from the footer, which is what I need to do as the footer has a few buttons that should be changing the screen:

const Stack = createStackNavigator();

const App = () => {    
  return (
    <Provider store={store}>
      <NavigationContainer>
        <Header />
        <Stack.Navigator>
          <Stack.Screen
            name="Home"
            component={HomeScreen}
            options={{
            headerShown: false
          }}
          />
          <Stack.Screen
            name="Login"
            component={LoginScreen}
            options={{
            headerShown: false
          }}
          />
        </Stack.Navigator>
        <Footer />
      </NavigationContainer>
    </Provider>
  );
};

How do I pass the navigation prop to the footer component?

Answer

Soufiane Odf picture Soufiane Odf · Apr 22, 2020

Try this:

Create a new file named: RootNavigation.js

// RootNavigation.js

import * as React from 'react';

export const navigationRef = React.createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}
// file where you have the navigation

import {navigationRef} from './path/to/RootNavigation';

      <NavigationContainer ref={navigationRef}>
      .....
        <Footer />
      </NavigationContainer>

And Footer.js should be something like this:

// Footer.js

import React from 'react';
import {View, Button} from 'react-native';
import * as RootNavigation from './path/to/RootNavigation';

const Footer= () => {
  return (
    <View>
      <Button
        title={'Go to'}
        onPress={() =>
          RootNavigation.navigate('screenName ', {userName: 'Lucy'})
        }
      />
    </View>
  );
};

export default Footer;

For more info you can read the documentation. https://reactnavigation.org/docs/navigating-without-navigation-prop/