Cover image for Show 404 Route Page In React Router outside Router Compont Heirarchy

Show 404 Route Page In React Router outside Router Compont Heirarchy

sabirjamia profile image Mohammad Sabir ・1 min read

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.

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

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 />
         ) : (
               <Header />
               <Footer />

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


markdown guide