Search code examples
javascriptnext.jshttp-status-code-404

Next.js - How to hide navigation and footer component on 404 page?


import Footer from "./Footer";
import Navigation from "./Navigation";
import { useRouter } from "next/router";

function Layout({ children }) {
  const router = useRouter();
  return (
    <>
      {router.pathname !== "/*" && <Navigation />}
      {/* {router.pathname !== "*" && <Navigation />} */}
      <main className="main-content">{children}</main>
      {router.pathname !== "/*" && <Footer />}
      {/* {router.pathname !== "*" && <Footer />} */}
    </>
  );
}

export default Layout;

Unfortunately the methods with an asterisk do not work :/ ?!?

Thank you in advance and best regards for everyone ;-)


Solution

  • If you are not using a custom 404 page, the default router.pathname is _error so

    {router.pathname !== "/_error" && <Navigation />}
    

    should work.

    If you are using custom 404 page (404.js inside /pages) router.pathname is /404.

    If you reuse the built in error page router.pathname inside your page or component router.pathname would be the current page path.
    Ex :

    import Error from 'next/error'
    
    const MyPage = ({isError = true})=>{
        // pagepath would be something like pages/mypage
        return isError ?  <Error statusCode={"404"} /> : <p>My page </p>
    }
    
    export default MyPage 
    

    In this case both methods mentioned above wont work.
    However i would not recommended to use this method.