React Router v5 - Fix for redirects not rendering when using custom history
If you're using React Router v5 with a custom history object (<Router history={history}>
) and are experiencing issues like redirects not working properly or not rendering, it might be because of the version of the history
library you're using.
React Router (react-router-dom
) 5.x works with history
4.x, I was using "react-router-dom": "^5.2.0"
with "history": "^5.0.0"
and my redirects were updating the url but not rendering the component or logging any errors in the browser console, it was a frustrating couple of hours before I stumbled onto the solution.
The issues were fixed by updating the history version to "history": "^4.10.1"
.
Example of using react router with custom history
function App() {
return (
<Router history={history}>
<Switch>
<PrivateRoute exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Redirect from="*" to="/" />
</Switch>
</Router>
);
}
Custom history used by react router
import { createBrowserHistory } from 'history';
export const history = createBrowserHistory();
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some React Help?
Search fiverr to find help quickly from experienced React developers.