How to React Router with Webpack 5 - Setup Tutorial

 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 

Just recently I had to use Docker for my React web application development. Here I want to give you a brief walkthrough on how to achieve it. First of all, we need a React application. Either create a…

A React tutorial which teaches you how to use React Router 6 . In order to get you started, create a new React project (e.g. create-react-app ). Afterward, install React Router by following the…

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.