DEV Community

Cover image for Show 404 Route Page In React Router outside Router Component Heirarchy
Mohammad Sabir
Mohammad Sabir

Posted on • Edited on

Show 404 Route Page In React Router outside Router Component Heirarchy

I am very excited and nervous at the same time as it is my first blog post. Recently I was working on a project in which the heirarchy of the components was like below diagram

Alt Text

Let me explain you the problem, I need to show the PageNotFound page without header and footer section and in layout I had defined the header and footer section with main as defined in the above diagram. If I had defined the PageNotFound in the AppRoutes components which had all the routes in my application, then I have to display the header and footer section in PageNotFound page.

There was not enough content on the internet for above issue, But luckily I have found some stuff regarding the state management in the react-router via browser history api. So the solution was two use react-router's Redirect component.

<Switch>
    <Route exact path='/'>
        <HomePage />
    </Route>
    <Route path='*'>
        <Redirect to={{ ...location, state: { from: '404' } }} />
    </Route>
</Switch>
Enter fullscreen mode Exit fullscreen mode

and in the Layout component I checked if the router state was { from: '404' } and if that was the case then I showed only the PageNotFound page otherwise the Header, Footer and main section.

const Layout = ({ children }) => {
   const { state } = useLocation();

   {state?.from == '404' ? (
            <PageNotFoundPage />
         ) : (
            <Fragment>
               <Header />
               <Flex
                  as='main'
               >
                  {children}
               </Flex>
               <Footer />
            </Fragment>
       )}
    );
};
Enter fullscreen mode Exit fullscreen mode

Please let me know in the comments, if I am not making sense or anything wrong about the article.

Top comments (0)