miphe
miphe

Reputation: 1863

Is there a way to use history with HashRouter, with react-router v4?

I have need to redirect a user outside of a React component, which typically is done using history with react-router.

// history.js
const history = createBrowserHistory();
export default history;

// App, setting up router
import { HashRouter as Router } from 'react-router-dom';
import history from './history';
...
<HashRouter history={history}>...</HashRouter> // problem

// Non-component file
import history from './history';
history.push('/target');

Since HashRouter doesn't take a history prop, but rather handles history internally, and developers are directed to use withRouter in order to expose history to a component, it's not apparent how to do redirects outside of a component.

I am using HashRouter and I need to use the history outside of a component (meaning I can't use withRouter).

How could I make this happen?

Upvotes: 8

Views: 9505

Answers (1)

miphe
miphe

Reputation: 1863

Yes, there is a way to use history and a hash-based router together.

When creating a history instance, use createHashHistory instead of createBrowserHistory.

// myCreatedHistory.js
import { createHashHistory } from 'history';
export default createHashHistory();

Instead of using HashRouter, use the low-level Router instead, and pass the history props to it, like so.

// App
import { Router } from 'react-router-dom';
import history from '../myCreatedHistory';
...
<Router basename="/" history={history}>...</Router>

Then you can import the history from anywhere (say a middleware).

// Middleware, or anywhere
import history from '../myCreatedHistory';
history.push('/target');

Upvotes: 15

Related Questions