StuartM
StuartM

Reputation: 6823

React Router - Mapping routes with 404 error page

I am currently using React Router. I prefer the syntax of a routes config file and mapping over the array of routes to render the Route, as opposed to the <Switch> option.

{routes.map(route => {
        return (
          <PrivateRoute
            key={route.path}
            path={route.path}
            exact
            component={route.component}
          />
        );
      })}

Is there a way with the above use case to have a 404 component for all non-exact matching routes.

I have seen the <Switch> approach like this: https://reacttraining.com/react-router/web/example/no-match. As mentioned I prefer declaring all routes in a route config file, with the path, component and breadcrumb name. If I go down the Switch route then the route config is only used for breadcrumbs and becomes less useful

Upvotes: 1

Views: 1439

Answers (1)

Josep
Josep

Reputation: 13071

If you are going to be defining your routes in a config file, then you should probably use react-router-config (which is also part of react-router)

If you have a peek at the implementation of renderRoutes, then you will notice that it internally uses a Switch component, which means that you can put your "404" routes at the end of the list and it should fallback to that one if there is no other match, for instance:

const routes = [
  {
    component: Root,
    routes: [
      {
        path: "/",
        exact: true,
        component: Home
      },
      {
        path: "/child/:id",
        component: Child,
        routes: [
          {
            path: "/child/:id/grand-child",
            component: GrandChild
          }
        ]
      },
      {
        path: "*",
        component: NotFound,
      },
    ]
  }
]

You could also implement a component like this RedirectToNotFound:

const RedirectToNotFound = () => <Redirect to="/404" />;

And then setup your config file like this:

const routes = [
  {
    component: Root,
    routes: [
      {
        path: "/",
        exact: true,
        component: Home
      },
      {
        path: "/child/:id",
        component: Child,
        routes: [
          {
            path: "/child/:id/grand-child",
            component: GrandChild
          }
        ]
      },
      {
        path: "/404",
        component: NotFound
      },
      {
        path: "*",
        component: RedirectToNotFound,
      },
    ]
  }
]

Full disclosure: I've never used react-router-config and unless you have a very specific need I wouldn't recommend its usage.

Upvotes: 1

Related Questions