Trailing forward slash in react-router routes

19k views Asked by At

I am using react-router v3.0.0 with react v15.1.0. I have the following route setup:

ReactDom.render(<Provider store={store}>
    <Router history={BrowserHistory}>
        <Route path='shop' component={App}>
            <IndexRoute component={Shop} />
            <Route path='/product' component={ProductView} />
        </Route>
    </Router>
</Provider>, document.getElementById('app'));

As you can see, my base Route for the application has a path of 'shop'. As far as the user is concerned, this should result in 2 separate routes, http://example.com/shop and http://example.com/shop/product. However, this is not the case.

When I deploy the aforementioned code, http://example.com/shop renders correctly, but http://example.com/shop/product renders nothing. In fact, I get a console error:

Warning: [react-router] Location "/shop/product" did not match any routes

So, I altered my setup a bit:

ReactDom.render(<Provider store={store}>
    <Router history={BrowserHistory}>
        <Route path='shop/' component={App}>
            <IndexRoute component={Shop} />
            <Route path='product' component={ProductView} />
        </Route>
    </Router>
</Provider>, document.getElementById('app'));

This will allow me to render http://example.com/shop/ (notice the trailing forward slash), http://example.com/shop/product, but NOT http://example.com/shop.

Is is possible to render http://example.com/shop, http://example.com/shop/, http://example.com/shop/product within the same app?

2

There are 2 answers

2
Paul S On BEST ANSWER

The reason that your first setup failed is because React Router <Route> paths that begin with a slash are considered absolute to the root (/), even when they are nested.

Your second setup is close, but you should not include the trailing slash in shop/. React Router will join the paths together for you, you do not need to worry about including a slash to join shop and product. (For example, look at this configuration which uses relative paths)

ReactDom.render(<Provider store={store}>
  <Router history={BrowserHistory}>
    <Route path='shop' component={App}>
        <IndexRoute component={Shop} />
        <Route path='product' component={ProductView} />
    </Route>
  </Router>
</Provider>, document.getElementById('app'));
0
Shubham Khatri On

You should use the route setup like

ReactDom.render(<Provider store={store}>
    <Router history={BrowserHistory}>
        <Route path='shop' component={App}>
            <IndexRoute component={Shop} />
            <Route path='/shop/product' component={ProductView} />
        </Route>
    </Router>
</Provider>, document.getElementById('app'));

You route didn't work because your product route was absolute with your url since it begins with a /. I think a better way would be to remove it and use the route as

<Route path='product' component={ProductView} />