4
votes

Is it possible to create a global history file to manage the createBrowserHistory() on react-router-dom v5? I know the V5 has the useHistory() as a way to get the history. But is it possible to retrieve the history from anywhere, like for cases where I am not using a function component?

On V4 I could create a file history.js:

import { createBrowserHistory } from 'history';
export default createBrowserHistory();

It works on V4 https://codesandbox.io/s/react-router-v4-nfwr0

It doesn't work on V5 - It updates the URL but redirects to not-found https://codesandbox.io/s/react-router-v5-not-working-jlrep

2

2 Answers

8
votes

As the doc says you should use the v4 of history to work on react-router v5.

https://github.com/ReactTraining/history

Documentation for version 4 can be found on the v4 branch. Version 4 is used in React Router versions 4 and 5.

0
votes

I solved this by doing this.See what i done

Create a file like before

This is the code

import {createBrowserHistory}  from 'history';
import store from 'store';
export default createBrowserHistory({
    basename:  store ? store.getState().productionBaseUrl : ''
});

The reason why i import Redux is the project does not pulish on nginx root folder.So i should add a basename.If you do not neet it,you can remove it.

Then you can use it in your own coponnet. How to use? Let me show your the code.

// if my history in src/router/
import history from 'router/history';

history.push(`${your router address}`)

Attention

The history's push method can pass an object like the origin props.But it's refresh when in the child router always. So pass a string when use it.