helion3
helion3

Reputation: 37381

Redirect root path to child in react-router 6

I'm trying to force redirect the exact root path / to a child path (we have several modules and the root will just direct you to the first one, there's nothing to show at the actual root).

However I can't find any examples for the root path, and trying other approaches (with Navigation to just trigger an infinite loop.

<Route element={<Navigate replace to='/module/submodule' />} path='/'>
  <Route element={<Module />} handle={{ crumb: (): string => 'Module' }} path='module'>
    <Route element={<Submodule />} handle={{ crumb: (): string => 'Submodule' }} path='submodule' />
  </Route>
</Route>

I need to redirect / to /module/submodule

Upvotes: 2

Views: 1516

Answers (3)

magino
magino

Reputation: 197

Is this correct for react-router-dom:6.15.0?

const router = createBrowserRouter([
    {
        path: '/',
        element: <App />,
        errorElement: <ErrorPage />,
        children: [
            {
                index: true,
                element: <Navigate replace to='/projects' />,
            },
            {
                path: '/projects',
                element: <ProjectsPage />,
            },
        ],
    },
])

Upvotes: 6

Drew Reese
Drew Reese

Reputation: 202751

Move the redirect into a nested "catch-all" route. Anything not matched by any route will be redirected to "/module/submodule".

<Route path="/">
  <Route
    path="module"
    element={<Module />}
    handle={{ crumb: (): string => 'Module' }}
  >
    <Route
      path="submodule"
      element={<Submodule />}
      handle={{ crumb: (): string => 'Submodule' }}
    />
  </Route>
  <Route path="*" element={<Navigate replace to="/module/submodule" />} />
</Route>

Upvotes: 1

Jacob Smit
Jacob Smit

Reputation: 2379

You should be able to use an index route.

<Route path='/'>
  <Route element={<Navigate replace to='/module/submodule' />} index />
  <Route element={<Module />} handle={{ crumb: (): string => 'Module' }} path='module'>
    <Route element={<Submodule />} handle={{ crumb: (): string => 'Submodule' }} path='submodule' />
  </Route>
</Route>

Upvotes: 4

Related Questions