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?
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.
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.
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> .
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With