'React Navigation v5: How to navigate using redux thunk/redux saga?
How can I navigate the screen in react-navigation in Redux-Saga and Redux-Thunk? Is it possible to get access to the navigation context in sagas or thunk?
For example in redux-thunk
import { StackActions } from '@react-navigation/native';
dispatch(StackActions.replace('Profile', {
user: 'jane',
}))
Or, in redux-sagas
import { StackActions } from '@react-navigation/native';
import { put } from 'redux-saga/effects';
yield put(StackActions.replace('Profile', {
user: 'jane',
}))
Solution 1:[1]
You have to use '@react-navigation/compat'
library.
import { createStackNavigator } from '@react-navigation/stack';
import { createCompatNavigatorFactory } from '@react-navigation/compat';
const RootStack = createCompatNavigatorFactory(createStackNavigator)(
{
Home: { screen: HomeScreen },
Profile: { screen: ProfileScreen },
},
{
initialRouteName: 'Profile',
}
);
import { StackActions } from '@react-navigation/compat';
dispatch(StackActions.replace('Profile', {
user: 'jane',
}))
For more information please check this link
Solution 2:[2]
In Summary (snippets copied from the v5 doc)
You can get access to the root navigation object through a ref and pass it to the RootNavigation which you will use later to navigate.
// App.js
import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';
export default function App() {
return (
<NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
);
}
Define RootNavigation, which is a simple module with functions that dispatch user-defined navigation actions.
// RootNavigation.js
import * as React from 'react';
export const navigationRef = React.createRef();
export function navigate(name, params) {
navigationRef.current?.navigate(name, params);
}
// add other navigation functions that you need and export them
Then, in any of your javascript modules, just import the RootNavigation and call functions which you exported from it.
// any js module
import * as RootNavigation from './path/to/RootNavigation.js';
// ...
RootNavigation.navigate('ChatScreen', { userName: 'Lucy' });
The Official React-Navigation v5 Doc.
https://reactnavigation.org/docs/5.x/navigating-without-navigation-prop/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Amila Dulanjana |
Solution 2 | Plague |