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?
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With