I would like to redirect my url for e.g to '/questions/1' when I only write /questions
React router - How to redirect to child component if parent component path is entered in url
5.3k Views Asked by Bradley Bousoula At
4
There are 4 best solutions below
0
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
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
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>,
},
],
},
You can render a redirect from one path to the other.
If using
react-router-domv5 use theRedirectcomponent:If using
react-router-domv6 use theNavigatecomponent: