Anoop V
Anoop V

Reputation: 231

How to remove Header from a single page in NextJS Layout?

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 />

Upvotes: 6

Views: 7346

Answers (2)

Outdated DNZ
Outdated DNZ

Reputation: 157

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.

Upvotes: 13

Pedro Lopes
Pedro Lopes

Reputation: 106

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.

Upvotes: 5

Related Questions