This is my main App
component:
const router = createBrowserRouter([
{
element: <Root />,
children: [
{ path: "/", element: <Users /> },
{ path: "/users", element: <Users /> },
{ path: "/places", element: <Places /> },
],
},
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;
I want to redirect user to homepage "/"
if user enters any other route which is not in the routers. For example the user enters "/products"
and I don’t have this route defined so I want to redirect the user to homepage "/"
.
3
Answers
Well you can add the Homepage in children with path as "*" like below.
use * character in path, * means all routes :
You should render a redirect to the home
"/"
route for any path (i.e. using a wildcard"*"
matcher) the app isn’t specifically rendering a matching route for. Since the home"/"
and"/users"
routes both render the sameUsers
component content you can shortcut this a bit by redirecting any "unknown" paths to"/users"
instead. This eliminates redundant routes.Example: