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.

3 Answers 3

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 },
        ] },
    ]
};
Sign up to request clarification or add additional context in comments.

2 Comments

historyApiFallback: true, seems to solve the problem.. thanks
0

Make sure your webpack configuration file contains following code:

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

See more in this article

Comments

-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} />);

2 Comments

Is there not a way to achieve this without using hashes?
The guide at react-router recommends using browserHistory over hashHistory. github.com/reactjs/react-router/blob/1.0.x/docs/guides/basics/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.