Can I set a base route in react-router

Assuming my app's base url is example.com/app

Is it possible to set a base route in react-router so instead of writing all routes as

/app/a
/app/b
/app/c

I can just specify them as

a
b
c

I tried the below example I found in the docs but it wouldn't work (page would display nothing). Maybe it's because I'm using [email protected], or I'm doing something wrong.

import { useRouterHistory } from 'react-router'
import { createHistory } from 'history'

const history = useRouterHistory(createHistory)({
  basename: '/app'
})

const Root = ({store}) => (
    <Provider store={store}>
        <Router history={history}>
            <Route path='/' component={App}>
                ...
            </Route>
        </Router>
    </Provider>
)

Solution 1:

With the newest react router (v4) you can easily do this

<BrowserRouter basename="/calendar">
  <Link to="/today"/> // renders <a href="/calendar/today">
</BrowserRouter>

Solution 2:

If you want to use <Router />, that give you access to history object, allowing you to change page through history.push('/my-path') method directly from js. You will face the issue that BrowserRouter does not have history prop available, and Router does not have basename available.

The solution is the following:

const App: React.FC = () => {
  // do not put a slash at the end of the basename value.
  const history = createBrowserHistory({ basename: '/your-base-name' });

  return <Router history={history}>
           ...
         </Router>;
}

The base URL for all locations. If your app is served from a sub-directory on your server, you’ll want to set this to the sub-directory. A properly formatted basename should have a leading slash, but no trailing slash

https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string