10

I'm having some issues working with react-router and webpack-dev-server to achieve nested url routing.

webpack.config.js

output: {
    path: path.resolve(__dirname, 'build'),
    publicPath: "/", <-- this enabled routing to /register/step2
    filename: "js/bundle.js",
},

routes.js

const routes = {
    childRoutes: [
        { path: '/', component: Home },
        { path: '/login', component: Login },
        { path: '/register', component: Register },
        { path: '/register/step2', component: SecondStep },
    ]
};

export default (<Router routes={routes} history={createBrowserHistory()} />);

When clicking around in the appliation, I can get to /register/step2 but once I hit refresh in the browser, my common.js and bundle.js is missing: 404, since it's trying to load everything from /register/ directory.

Can anyone help? Thanks.

Bruce Lim
  • 745
  • 6
  • 22

3 Answers3

8

I figured it out. 2 things that is needed to enable this.

webpack.config.js

devServer: {
    historyApiFallback: true <-- this needs to be set to true
}


routes.js

const routes = {
    childRoutes: [
        { path: '/', component: Home },
        { path: '/login', component: Login },
        { path: '/register', component: Register, childRoutes: [
            { path: 'step2', component: SecondStep },
        ] },
    ]
};
Bruce Lim
  • 745
  • 6
  • 22
  • 1
    historyApiFallback: true, seems to solve the problem.. thanks – pravin Jul 02 '16 at 15:17
  • but not with hot reload: http://stackoverflow.com/questions/40159965/enable-single-page-app-react-hot-reload-webpack – Marc Oct 24 '16 at 09:16
0

Make sure your webpack configuration file contains following code:

output: {
    publicPath: '/'
},
devServer: {
    historyApiFallback: true
}

See more in this article

RamoFX
  • 510
  • 2
  • 9
  • 17
-1

If you use hashHistory instead of createBrowserHistory() it will keep the server from requesting to your current url on your server.

export default (<Router routes={routes} history={hashHistory} />);
RichG
  • 309
  • 2
  • 5
  • Is there not a way to achieve this without using hashes? – Bruce Lim Jan 27 '16 at 07:02
  • The guide at react-router recommends using browserHistory over hashHistory. https://github.com/reactjs/react-router/blob/1.0.x/docs/guides/basics/Histories.md#createbrowserhistory – Bruce Lim Feb 12 '16 at 21:54