Skip to content

[Bug]: How to navigate outside React context in v6? #8264

Closed
@hacker0limbo

Description

@hacker0limbo

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:

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions