Search code examples
reactjsreact-routerreact-router-v4react-admin

reactjs - Handling custom 404 page


I am trying to create a route that would catch all the invalid URL's and then display my custom 404 page to user without Admin Layout. My problem is, that my 404 page always displays the Admin Layout (even if the User is not logged in). I have these routes in my routes.js:

export default [
 <Switch>
   <Route exact path="/password-reset" component={ResetPassword} noLayout />,
   <Route exact path="*" component={NotFound} noLayout/>
 </Switch>
];

I have added this bit to the Admin component in my App.js:

const App = () => (

<Admin
    catchAll=         {NotFound}
    customRoute=      {routes}
>
</Admin>
);

Any idea how to handle the 404 page so it would catch all the invalid URL's and wouldnt display the Admin Layout?

Thank you in advance.


Solution

  • For react-router < 4.0

    If you want to display an error page and not change the path

    <Route path='*' exact={true} component={errorcomponent} />
    

    If you want to display an error page and change the path

    <Route path='/error' component={errorcomponent} />
     // use redirect to  change the Url
    <Redirect from='*' to='/error' />
    

    For react-router 4

    Keep the path

    <Switch>
        <Route exact path="/" component={component} />
        <Route component={errorcomponent} />
     </Switch>
    

    change Url.

     <Switch>
        <Route path="/comp" component={component} />
       <Redirect to="/error" />
     </Switch>
    

    the redirect tag has to be put whereever you place a route tag insde a switch.