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

July 26, 2022

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

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 'RootNavigation';

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

And BitFrit.js should be something like this:

// BitFrit.js

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

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

export default BitFrit;

For more info you can read the documentation https://reactnavigation.org/docs/navigating-without-navigation-prop/
Ref-by : https://stackoverflow.com/questions/61170112/how-to-use-navigation-navigate-from-a-component-outside-the-stack-navigation


Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow