When switching from reach/router to react-router, how do you set basename?

0

Issue

I am migrating from reach/router to react-router v6 and I have a set of routes like this

<Router basename={appPath}>
  <Dashboard path="/" />}
  <DashboardMessages path="messages"/>
  <DashboardTasks path="tasks" />
  <AboutPage path="about" />
</Router>

but in the new style in react-router at v6, it looks like:

<Routes>
  <Route path="/" element={<Dashboard />}>
    <Route
      path="messages"
      element={<DashboardMessages />}
    />
    <Route path="tasks" element={<DashboardTasks />} />
  </Route>
  <Route path="about" element={<AboutPage />} />
</Routes>

but routes doesn’t take a basename. How can I set this?


update: In the docs it says:

"The prop may be used to make all routes and links
in your app relative to a "base" portion of the URL pathname that they
all share. "

But if you do something like this:

<Router basename={appPath}>
 <Routes>
  <Route path="/" element={<Dashboard />}>
    <Route
      path="messages"
      element={<DashboardMessages />}
    />
    <Route path="tasks" element={<DashboardTasks />} />
  </Route>
  <Route path="about" element={<AboutPage />} />
 </Routes>
<Router>

Typescript complains that:

 Type '{ children: Element; basename: string; }' is missing the following properties from type 'RouterProps': location, navigator

I am guessing I can get location from useLocation(), but there doesn’t seem to be a way to get navigator.

Solution

Use one of the higher-level routers that manage the navigation context.

Example:

import { BrowserRouter, Routes, Route } from 'react-router-dom';

<BrowserRouter basename={appPath}>
  <Routes>
    <Route path="/" element={<Dashboard />}>
      <Route
        path="messages"
        element={<DashboardMessages />}
      />
      <Route path="tasks" element={<DashboardTasks />} />
    </Route>
    <Route path="about" element={<AboutPage />} />
  </Routes>
<BrowserRouter>

The Router is the low-level interface shared by the all the other routers.

Answered By – Drew Reese

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More