0

My App.tsx:

<Switch>
  <Route exact path="/" component={LoginPage} />
  <Route path="/dashboard" component={Dashboard} />
  <Route path="*" component={NoMatch} />
</Switch>

Dashboard.tsx component:

const { path } = useRouteMatch();

<Switch>
  <Route exact path={`${path}`} component={DashboardIndex} />
  <Route path={`${path}/users`} component={Users} />
</Switch>

The actual problem lies in the "/dashboard" nested routes. Since i'm not using an exact prop on it, it would match anything, like "/dashboard/blablabla" though this route doesn't exist in my app. Only "/dashboard/users" does exist. How to deal with non existent routes, when exact is not being used?

UPDATE

Ended up using this approach:

<Switch>
  <Route exact path={`${path}`} component={DashboardIndex} />
  <Route path={`${path}/users`} component={Users} />
  <Route path={`${path}/*`} component={NoMatch} />
</Switch>

Also if you want to completely redirect to another page, just use <Redirect to="/path" />:

<Route path={`${path}/*`}>
  <Redirect to="/path" />
</Route>
Alexander Kim
  • 17,304
  • 23
  • 100
  • 157

2 Answers2

0

In scenarios like this the best way is to have a 404 page which you render for non existing Routes

You can change your code to something similar like

const { path } = useRouteMatch();

<Switch>
  <Route exact path={`${path}`} component={DashboardIndex} />
  <Route path={`${path}/users`} component={Users} />
  <NotFoundRoute />
</Switch>

Please refer this SO post to check implementation of not found route.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • With this "Declarative" way, is it ok to put a `` everywhere in a nested structure? For example, i have a not found route in App.tsx, then inside a dashboard, then if i would have "/cars" there would i declare not found route either? Also what if `` would have nested routes either? I should handle not found cases inside `Users` component? – Alexander Kim Feb 21 '20 at 04:31
  • You can have a NotFoundRoute anywhere in the nested structure. The only thing you need to keep in mind is that this NotFoundRoute must always be inside a switch statement – Shubham Khatri Feb 21 '20 at 04:32
0

I have used something like this before, may this helps

const { path } = useRouteMatch();

<Switch>
  <Route exact path={`${path}`} component={DashboardIndex} />
  <Route path={`${path}/users`} component={Users} />
  <Route path="*" component={NoMatch } />
</Switch>

No match component

function NoMatch() {
  let location = useLocation();

  return (
    <div>
      <h3>
        No match for <code>{location.pathname}</code>
      </h3>
    </div>
  );
}
RKM
  • 144
  • 1
  • 6