Thursday, March 16, 2023
HomeReactTips on how to React Router with Webpack 5

Tips on how to React Router with Webpack 5


In case you occur to have a customized Webpack setup, you could be questioning the way to arrange React Router with Webpack. As an instance we’ve got the next minimal React software utilizing React Router:

import React from 'react';

import {

BrowserRouter as Router,

Route,

Hyperlink,

} from 'react-router-dom';

const Dwelling = () => <div>Dwelling</div>;

const About = () => <div>About</div>;

const App = () => (

<Router>

<Hyperlink to="/">Dwelling</Hyperlink>

<Hyperlink to="/about">About</Hyperlink>

<Route actual path="/" part={Dwelling} />

<Route path="/about" part={About} />

</Router>

);

export default App;

In case you open your React software and navigate between each paths, every part ought to be high-quality. Nonetheless, in case you navigate through the browser’s URL bar to /about, you’re going to get one thing like Can’t GET /about. That is as a result of Webpack does not know what to serve on this path, as a result of Webpack solely is aware of concerning the root path / on your software. With a purpose to serve your React software on each path, that you must inform Webpack and its configuration that it ought to fallback for each path to your entry level:

...

module.exports = {

...

devServer: {

historyApiFallback: true,

},

};

Now you need to have the ability to navigate through the browser’s URL bar to /about. I hope this helps anybody who stumbles throughout this difficulty.

RELATED ARTICLES

Most Popular

Recent Comments