How can i create 404 Page Not Found in react-router-dom V5

Viewed 46

I use react-router-dom V5. When I create Route component in my project I use <HashRouter>.

This is example of my component:

<HashRouter>
  <Switch>
    <Route path="/form" component={Login} />
    <Route path="/admin" component={Panel} />
    <Route path="/changepass" component={ChangePass} />
    <Route path="*" component={NotFound} />
  </Switch>
</HashRouter>

For example when I enter: "/akfakafk" it works correctly, but when I enter: "/admin/wtwtwtw" it's not working.

I know it is not implemented correctly,

I want to know, how can I implement this?

By the way in "/admin" render Panel component that has return another routes.

This is my panel routes:

const dashboardRoutes = [
  {
    path: "/dashboard",
    name: dashboard,
    icon: DashboardIcon,
    component: DashboardPage,
    layout: "/admin",
  },
  {
    path: "/devicesManagement",
    name: devicesManagement,
    icon: DevicesIcon,
    component: DevicesPage,
    layout: "/admin",
  }
]
1 Answers

The issue here is that in RRDv5 all route paths are effectively path "prefixes", meaning for example for path "/admin" that all "/admin/*" paths can be matched by it and rendered.

If there are no descendent routes you can use the exact prop on routes you want to exactly match.

Example:

<HashRouter>
  <Switch>
    <Route path="/form" component={Login} />
    <Route path="/admin" exact component={Panel} />
    <Route path="/changepass" component={ChangePass} />
    <Route path="*" component={NotFound} />
  </Switch>
</HashRouter>

Here "/admin" will be matched and render the Panel component, but "/admin/wtwtwtw" will not and the NotFound component will be rendered as expected.

If there are descendent routes then you sould again render another Switch component and routes and either another general "not found" route or redirect to a more general "not found" route.

Example:

<HashRouter>
  <Switch>
    <Route path="/form" component={Login} />
    <Route path="/admin" component={Panel} />
    <Route path="/changepass" component={ChangePass} />
    <Route path="*" component={NotFound} />
  </Switch>
</HashRouter>

...

const Panel = props => {
  const { path } = useRouteMatch();
  ...

  return (
    ...
    <Switch>
      <Route path={`${path}/dashboard`} component={DashboardPage} />
      <Route path={`${path}/devicesManagement`} component={DevicesPage} />
      ...
      <Route path="*" component={NotFound} />
    </Switch>
  );
};
Related