skip to Main Content

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


  1. Well you can add the Homepage in children with path as "*" like below.

    const router = createBrowserRouter([
      {
        element: <Root />,
        children: [
          { path: "/", element: <Users /> },
          { path: "/users", element: <Users /> },
          { path: "/places", element: <Places /> },
          { path: "*", element: <Homepage /> },
        ],
      },
    ]);
    
    function App() {
      return <RouterProvider router={router} />;
    }
    
    export default App;
    
    Login or Signup to reply.
  2. use * character in path, * means all routes :

    const router = createBrowserRouter([
      {
        element: <Root />,
        children: [
          { path: "/", element: <Users /> },
          { path: "/users", element: <Users /> },
          { path: "/places", element: <Places /> },
          { path: "*", element: <Page404 /> },
        ],
      },
    ]);
    
    function App() {
      return <RouterProvider router={router} />;
    }
    
    export default App;
    
    Login or Signup to reply.
  3. 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 same Users component content you can shortcut this a bit by redirecting any "unknown" paths to "/users" instead. This eliminates redundant routes.

    Example:

    import {
      createBrowserRouter,
      Navigate
    } from 'react-router-dom';
    
    const router = createBrowserRouter([
      {
        element: <Root />,
        children: [
          { path: "/users", element: <Users /> },
          { path: "/places", element: <Places /> },
          { path: "*", element: <Navigate to="/users" replace /> },
        ],
      },
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search