2

I am working on a NextJS project using Layout so that I can use the same Header and Footer for all pages. But for one of the pages, I don't need the Header, I need the Footer alone. Is there any way to do this?

This is my _App.js:

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />;
    </Layout>
  );
}

This is how I am rendering them:

  <Header />
  <SidebarMenu />
  <FloatingChat />

  {/* Display props */}
  {children}

  <Footer />
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Anoop V
  • 141
  • 3
  • 10
  • 1
    You can create a separate components such as `
    ` and `
    ` and call one or both of them as you want. Or, if you want to dig deeper, build your own `_document.tsx` file, [read here](https://nextjs.org/docs/advanced-features/custom-document).
    – hisam Sep 15 '21 at 07:32
  • 1
    Does this answer your question? [Next.js Opt out of Layout Component for specific pages from \_app.js](https://stackoverflow.com/questions/66914855/next-js-opt-out-of-layout-component-for-specific-pages-from-app-js) – Shreyas Jadhav Dec 17 '22 at 04:43
  • @ShreyasJadhav yes, it does.. – Anoop V Dec 18 '22 at 05:12

2 Answers2

11

I know it's been 3 months but I still wanna answer this cause me being a beginner faced difficulties when they only link documentation which are generally really vague.

Considering this is your layout.jsx

  <Header />
  <SidebarMenu />
  <FloatingChat />
  {children}
  <Footer />

you can use next/router to show or hide the components

import React from "react";
import Header from "./Header";
import Footer from "./Footer";
import SidebarMenu from "./SidebarMenu";
import { useRouter } from "next/router";

export default function Layout({children}){
    const router = useRouter();
    if(router.pathname != "/pagename" )
    return (
         <Header />
         <SidebarMenu />
         <FloatingChat />
         {children}
         <Footer />
    )
    else {
        return (
         <SidebarMenu />
         <FloatingChat />
         {children}
        )
    }
}

We just tell the layout.jsx file to show the specific layout on not that page and everywhere else and if it does come on that page we can show a different layout also you can next the pathnames if you want it on multiple pages.

Outdated DNZ
  • 137
  • 1
  • 8
  • May need updating https://stackoverflow.com/questions/74421327/nextrouter-was-not-mounted-next-js import { usePathname } from "next/navigation"; const pathname = usePathname(); ... if(pathname != "/pagename" ) ... – Graham Hesketh Aug 25 '23 at 10:26
4

You can use next/router's pathname property to get the page it's currently on, and then not render the Header if the page is a non-header page.

Pedro Lopes
  • 96
  • 2
  • 3