Search code examples
node.jsreactjsreact-routerweb-config

Blank page on refresh when using nested path


I'm pretty new to react and webpack, and I'm trying to use react-router-dom for routing in my web app.

But something weird happens, when I defined the path for my component to '/:guid' everything works fine, but if I set it to '/users/:guid' I'm getting a blank page when I refresh the page.

I read some posts that said to add 'publicPath' and 'historyApiFallback: true' to my webpack.config.js but it still doesn't work for some reason. although, before adding it, I got 'cannot GET url' error.

Router.js:

import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import UserInfo from '../Containers/UserInfo/UserInfo';
import Main from './Main/Main';

const Router = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path='/' component={Main} />
        <Route path='/users/:guid' component={UserInfo} />
      </Switch>
    </BrowserRouter>
  );
};

export default Router;

webpack.config.js:

const path = require('path');

const DIST_DIR = path.resolve(__dirname, 'dist');
const SRC_DIR = path.resolve(__dirname, 'src');

const config = {
  entry: `${SRC_DIR}/app/index.js`,
  output: {
    path: `${DIST_DIR}/`,
    filename: 'bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        include: SRC_DIR,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-2']
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  devServer: {
    historyApiFallback: true
  }
};

module.exports = config;

Solution

  • Well, after some more research, I got to this github webpack-dev-server issue page that suggests to add a <base /> to my "index.html" file:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>React Training Project</title>
        <base href="/">
    </head>
    <body>
        <div id="app"></div>
        <script src="./bundle.js"></script>    
    </body>
    </html>
    

    Apparently this is what I was missing.