Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you push a screen using only the navigation ref

Using the react-navigation library, when you're on a screen that's part of a stack navigator you can use props.navigation.push(route name, params). I want to achieve the same thing, being able to push a new screen but from the root level where I take the NavigationContainer ref.

So I have this code

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

And I want to do something like

   navigationRef.push(routeName, params);

Unfortunately, I don't have the push method here. Is there a workaround for this?

like image 279
Cristian Avatar asked Mar 09 '26 07:03

Cristian


1 Answers

You could set up a RootNavigation.js file like this:

import * as React from 'react';
import { StackActions } from '@react-navigation/native';

export const navigationRef = React.createRef();

export function push(...args) {
  navigationRef.current?.dispatch(StackActions.push(...args));
}

Then you can use it like this:

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

<NavigationContainer ref={navigationRef}>
  {/* content */}
</NavigationContainer>

and this:

import * as RootNavigation from './path/to/RootNavigation';

RootNavigation.push('Screen', { data: '...' })

Source: https://reactnavigation.org/docs/navigating-without-navigation-prop/.

like image 121
Bas van der Linden Avatar answered Mar 11 '26 08:03

Bas van der Linden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!