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
Asked Answered
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 />} />
This is perfect answer. –
Disembody
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
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>
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>,
},
],
},
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
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
]);
© 2022 - 2025 — McMap. All rights reserved.