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

5.3k Views Asked by At

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

4

There are 4 best solutions below

1
Drew Reese On BEST ANSWER

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 />} />
0
TZ5 On

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

0
Ye Myint Soe On

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>
1
Mahdi Haeri On

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>,
        },
    ],
},