Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 950
miphe Avatar asked Aug 27 '20 08:08

miphe


People also ask

Does react router use history API?

React Router uses the history package, which builds on the browser history API to provide an interface to which we can use easily in React apps. location - (object) The current location. May have the following properties: pathname - (string) The path of the URL.

How do you use .push history in react?

Using history.push() is another approach where we make use of the history props React Router provides while rendering a component. In other words, this works when the component is being rendered by React Router, bypassing the component as a Component prop to a Route.

What is difference between BrowserRouter and HashRouter?

HashRouter: When we have small client side applications which doesn't need backend we can use HashRouter because when we use hashes in the URL/location bar browser doesn't make a server request. BrowserRouter: When we have big production-ready applications which serve backend, it is recommended to use <BrowserRouter> .


1 Answers

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');
like image 55
miphe Avatar answered Oct 04 '22 02:10

miphe