Home > Mobile >  React Router - Auto navigate to first nested route when visiting parent route
React Router - Auto navigate to first nested route when visiting parent route

Time:06-22

I have nested routes.

  1. /account parent route
  2. /account/profile child route 1
  3. /account/settings child route 2

I want to navigate to the first child route account/profile when users visit the parent route /account.

Here is my current code. Thanks in advance. :)

https://codesandbox.io/s/elegant-haze-ouxxtv?file=/src/App.js

CodePudding user response:

I figured it out. I just need to add another route to navigate it to the first child route.

<BrowserRouter>
  <Routes>
    <Route index element={<Navigate to="account" />} />
    <Route path="account" element={<Account />}>
      <Route path="profile" element={<Profile />} />
      <Route path="settings" element={<Settings />} />

      {/* I added this line */}
      <Route index element={<Navigate to='profile' />}></Route>

    </Route>
  </Routes>
</BrowserRouter>

Demo: https://codesandbox.io/s/elegant-haze-ouxxtv?file=/src/App.js

CodePudding user response:

You can try this option using useEffect() and useNavigation(): https://codesandbox.io/s/wandering-cookies-v2v4jh?file=/src/Account.js
I think that using this way your App.js will not be overloaded.

CodePudding user response:

Copy this it will work. thank you

<BrowserRouter>
  <Routes>
    <Route index element={<Navigate to="account" />} />
    <Route path="account" element={<Account />}>
      <Route index element={<Navigate to='profile' />} />
      <Route path="profile" element={<Profile />} />
      <Route path="settings" element={<Settings />} />
    </Route>
  </Routes>
</BrowserRouter>
  • Related