How to React Router with Webpack 5

 by Robin Wieruch
 - Edit this Post

If you happen to have a custom Webpack setup, you may be wondering how to set up React Router with Webpack. Let's say we have the following minimal React application using React Router:

import React from 'react';
import {
BrowserRouter as Router,
Route,
Link,
} from 'react-router-dom';
const Home = () => <div>Home</div>;
const About = () => <div>About</div>;
const App = () => (
<Router>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
);
export default App;

If you open your React application and navigate between both paths, everything should be fine. However, if you navigate via the browser's URL bar to /about, you will get something like Cannot GET /about. That's because Webpack doesn't know what to serve on this path, because Webpack only knows about the root path / for your application. In order to serve your React application on every path, you need to tell Webpack and its configuration that it should fallback for every path to your entry point:

...
module.exports = {
...
devServer: {
historyApiFallback: true,
},
};

Now you should be able to navigate via the browser's URL bar to /about. I hope this helps anyone who stumbles across this issue.

Keep reading about 

A React Router tutorial which teaches you how to use Authentication in React Router 6 . The code for this React Router v6 tutorial can be found over here . In order to get you started, create a new…

A React Router tutorial which teaches you how to perform a Redirect in React Router 6 . The code for this React Router v6 tutorial can be found over here . In order to get you started, create a new…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.