101

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 react-router@3.0.0-alpha.1, 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>
)
galki
  • 8,149
  • 7
  • 50
  • 62

3 Answers3

163

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

<BrowserRouter basename="/calendar">
  <Link to="/today"/> // renders <a href="/calendar/today">
</BrowserRouter>
flob
  • 3,760
  • 2
  • 34
  • 57
galki
  • 8,149
  • 7
  • 50
  • 62
  • 4
    Is there anyway to do this with dynamic path fields? Like `/calendar/:year/:month/:day/event` where it could be, for example, `/calendar/11/4/21/event` – Jeremy Dec 15 '17 at 21:21
  • 4
    why not put the `:year/:month/:day/event` part in the Link to=? – galki Mar 02 '18 at 02:22
  • 6
    Important to point out here that the docs seem to be wrong about the correct usage of the tag. A self-closing tag as seen in the docs will have no effect. You need to wrap your tag around all your s and other routing tags. The example should read: ... – Jamie McLaughlin Mar 17 '20 at 15:27
  • 1
    this does not seem to work anymore unfortunately – Matteo Jun 27 '21 at 09:08
  • @Madeo can you provide a new answer? I’ll redirect – galki Jun 27 '21 at 13:45
  • `BrowserRouter` somehow did not work for me, I had to use the `createBrowserHistory`'s API and remove ` – Matteo Jun 28 '21 at 00:08
  • @Madeo I use the same approach as you do, but I find that `Route` component with trimmed path value will navigate to 404 route – liuliang Jul 29 '21 at 07:14
19

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

Ambroise Rabier
  • 3,636
  • 3
  • 27
  • 38
0

With React Router v6, it is recommended to use createBrowserRouter for web projects, as it works with data APIs.

Pass an options object as the second argument to createBrowserRouter to configure the basename.

For example:

import * as ReactDOM from 'react-dom';
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
const router = createBrowserRouter([
    { path: '/', element: <HomePage /> }
    /* other routes... */
], { basename: '/app' });

ReactDOM.createRoot(document.getElementById('root')).render(
    <RouterProvider router={router} />
);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80