React router - How to redirect to child component if parent component path is entered in url
Asked Answered
G

5

6

I would like to redirect my url for e.g to '/questions/1' when I only write /questions

Grati answered 21/1, 2022 at 17:12 Comment(0)
C
12

You can render a redirect from one path to the other.

If using react-router-dom v5 use the Redirect component:

<Redirect from="/questions" to="/questions/1" />

If using react-router-dom v6 use the Navigate component:

<Route path="/questions" element={<Navigate to="/questions/1" replace />} />
Chemarin answered 21/1, 2022 at 17:25 Comment(1)
This is perfect answer.Disembody
F
0

A little late, but thought this might be useful to someone.

createBrowserRouter([
    path: 'auth',
    children: [
        {
            index: true,
            loader: async () => redirect("/auth/login")
        },
        {
            path: "login",
            element: <Login />
        },
    ]
)]

!!! Warning

This might cause redirect loops, check if one redirect isn't calling another if that happens

Flourishing answered 31/1, 2024 at 15:25 Comment(0)
S
0

You have to use index route in react-router-dom v6

Must be like the following -

 <Route path="parent" element={<Parent />}>
    <Route index element={<Child1 />} />
    <Route path="child1" element={<Child1 />} />
    <Route path="child2" element={<Child2 />} />
  </Route>
Slacker answered 28/2, 2024 at 17:49 Comment(0)
S
0

This works for me if you want also to render parent. This renders "Today" in the AppPage when you enter URL "/app" and redirect you to "/app/today".

{

    path: "app",
    element: <AppPage />,
    errorElement: <NotFoundPage />,
    children: [
        {
            index: true,
            element: <Navigate replace to={'today'} />
        },
        {
            path: "today",
            element: <h1>Today</h1>,
        },
    ],
},
Sherrellsherrer answered 22/3, 2024 at 14:10 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Hayfork
C
0

If it gives a blank screen when using the <Navigate />, maybe you have missed the <Outlet />

If so, try this

export default createBrowserRouter([
  {
    path: 'auth',
    element: <Outlet />,
    children: [
      { index: true, element: <Navigate to="/auth/login" replace /> },
      { path: 'login', element: <Login /> },
      { path: 'sign-up', element: <SignUp /> },
    ],
  },

  // your remain routes
]);
Coverup answered 28/7, 2024 at 14:33 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.