Description
What version of React Router are you using?
v6
Steps to Reproduce
In v6 docs, it mentions that we can use useNavigate()
hook to do navigation, similar to in v5 we directly use useHistory()
hook. However I am not sure how we can do the navigation outside React context in v6, cause in v5, your can manually provide a history
object as a prop to Router
component, and reference it in other places even it is not inside React context:
// myHistory.js
import { createBrowserHistory } from "history";
const customHistory = createBrowserHistory();
export default customHistory
// otherFile.js
import history from './myHistory.js'
function doSomething() {
history.push('/xxx')
}
But how we could achieve the same functionality in v6? I have see a few posts asking similar questions on stackoverflow, but currently there is no solution provided:
- React Router v6.0.0-alpha.5 history prop removal - navigating outside of react context
- React Router ^6.0.0-beta.0 history prop removal - navigating outside of react context
Expected Behavior
A common scenario from my experience was consider i have a redux thunk action creator that doing signup logic, and after sending request if success i wish the page can be navigate to home page:
// signupActions.js
export const signupRequest = (userData) => {
return dispatch => {
dispatch(signupPending())
return axios.post('/api/user', userData)
.then(res => dispatch(signupSuccess()))
.then(() => {
// doing navigation
// navigate('/')
})
.catch(error => dispatch(signupFailure(error.message)))
}
}
The action is outside React context so i am not able to use useNavigate()
hook, Although i can do some refactor and move some logic to the React component, but i prefer to keep most business logic inside action since i wish the component are more responsible for UI rendering.
Actual Behavior
As mentioned above