Can I set a base route in react-router

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


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

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

Tags:

React Router