Search code examples
reactjsreact-router-dom

React router sub route redirect it to incorrect url with params


I am trying to make redirect path if the correct path is missing using react-router v6

This is my route

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path='/' element={<App />} errorElement={<ErrorPage />}>
      <Route path='/' element={<HomePage />} />
      <Route path='/about' element={<AboutPage />} />
      <Route path='/recipe/:id' element={<RecipePage />}>
        <Route index element={<Navigate to='/recipe/:id/ingredients' replace />}/>
        <Route path='/recipe/:id/ingredients' element={<Ingredients />} />
        <Route path='/recipe/:id/instructions' element={<Instructions />} />
      </Route>
    </Route>
  )
)

I want to redirect to correct path if the word ingredients or instructions is missing in the url.

For example when the url is http://localhost:5173/recipe/5431/, I want to redirect it to http://localhost:5173/recipe/5431/ingredients

But above code keep redirecting me to http://localhost:5173/recipe/:id/ingredients instead of http://localhost:5173/recipe/5431/ingredients

What's wrong in my code?


Solution

  • You don't need a complete absolute path in nested routes. Paths that don't start with "/" are relative paths, and nested routes can be referenced relative to their parent route path.

    Consider the following:

    <Route path='/recipe/:id' element={<RecipePage />}>
      <Route index element={<Navigate to='ingredients' replace />} />
      <Route path='ingredients' element={<Ingredients />} />
      <Route path='instructions' element={<Instructions />} />
    </Route>
    

    Complete code:

    const router = createBrowserRouter(
      createRoutesFromElements(
        <Route path='/' element={<App />} errorElement={<ErrorPage />}>
          <Route index element={<HomePage />} />
          <Route path='about' element={<AboutPage />} />
          <Route path='recipe/:id' element={<RecipePage />}>
            <Route index element={<Navigate to='ingredients' replace />} />
            <Route path='ingredients' element={<Ingredients />} />
            <Route path='instructions' element={<Instructions />} />
          </Route>
        </Route>
      )
    )