Suraj Prajapati
Suraj Prajapati

Reputation: 35

redirect user to homepage if page not found react router, in React

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 "/".

Upvotes: 3

Views: 2157

Answers (3)

Drew Reese
Drew Reese

Reputation: 202872

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 /> },
    ],
  },
]);

Upvotes: 2

Abbas Bagheri
Abbas Bagheri

Reputation: 842

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;

Upvotes: 1

Sam Phillemon
Sam Phillemon

Reputation: 247

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;

Upvotes: 2

Related Questions