Skip to content
Advertisement

Routing not working in a react app with webpack

I’m trying to create a react app with webpack which has some routing as well.

JavaScript

The routing works but when I go to a specific route and reload the page, it gives an error cannot get /about

JavaScript

As mentioned in this answer, adding

JavaScript

fixes the issue when its being run locally, but as soon as I deploy it, I get the same error

Advertisement

Answer

This happens because your server does not know what to do when it is hit by the /about route, initially when the browser has no asset files (HTML, JS, etc.). It occurs only when you are at /about and you refresh the page.

React router is a client side router, and hence the browser needs to load the client assets completely before it can work on your routes.

All you need to do is to configure your server to give all your assets to client even if it hit by an unknown route. i.e. when the 404 (Not found) situation arises at the server, your server should still provide all the assets that would otherwise be delivered when the route is at /.

And your react router should handle the 404 (Not found) event at the client side. as follows,

JavaScript

Please remember that, if you want to nest the routes then remove the exact property from the parent Route.

Advertisement