skip to Main Content

I have implemented routing in my React app and I wanted to redirect non-existent routes to errorpage.

Route:

    <Route path="/errorpage" component={ErrorPage} />
    {/*<Route path="/:parentId/:childId" component={ErrorPage} />*/}
    <Redirect to="/errorpage" />

Working:
When I try to access domain/notapath –> Redirect to proper error page with css

Not Working [Issue]
When I try nested routes like domain/123/123 –> Only ErrorPage content is displayed without css.

I also tried :

                    <Route path="/*" component={ErrorPage} />

So is there any other way to overcome this for routing to errorpage for nested paths as well which doesn’t exists.?

And why this above config didn’t work. Any suggestion. Thanks.

2

Answers


  1. You can use a route * in with a Switch component.
    the Switch component ensures that only the first matching route is rendered

    <Switch>
      //...
      <Route path="/errorpage" component={ErrorPage} />
      <Route path="*">
        <Redirect to="/errorpage" />
      </Route>
    </Switch>
    
    Login or Signup to reply.
  2. You need to do this…

    <Route path="*" element={<ErrorPage />} />

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search