Search code examples
typescriptnext.js14

How to hide header from root layout only at one page in nextjs 14


Im working on a app with next js 14 and typescript and in my root layout i added a header and footer but now on one of the pages i made i need to make the header and footer not be there

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Header from "@/components/header/Header";
import Footer from "@/components/footer/Footer";

const inter = Inter({ subsets: ["latin"], weight: ["400", "600"] });

export const metadata: Metadata = {
    title: "Premium Ibiza",
    description: "Premium Ibiza VIP Concierge",
};

export default function RootLayout({
    children,
}: Readonly<{
    children: React.ReactNode;
}>) {
    return (
        <html lang="en">
            <body className={inter.className}>
                <Header />
                {children}
                <Footer />
            </body>
        </html>
    );
}

This is my root layout

Ive tried a couple of ways one was making a Layout component in the components folder and to use that component to wrap the jsx of the pages i use and not use for the one i dont need it but the questions is it optimal like that

import Header from "../header/Header";
import Footer from "../footer/Footer";


export default function Layout({
    children,
}: Readonly<{
    children: React.ReactNode;
}>) {
    return (
        <div>
            {/* <Header /> */}
            {children}
            {/* <Footer /> */}
        </div>
    );
}


Solution

  • Best solution for this would be to use Nested layouts, here's how you might incorporate it -

    1. Don't add footer and header components in your RootLayout
    2. Create a nested directory wrapping components that will display the headers and footers components, you can use route groups if you don't want the directory name to be part of the URL.
    3. Create a layout.tsx file inside this directory and return the Header and Footer components (don't forget to include the children in jsx as well).
    4. Create another nested directory at the same level as #2 wrapping components that will not display the headers and footers components. This directory doesn't need a seperate layout.tsx for your use case but you can add one if you want something specific to be shared across all components in this directory (of course don't include the header and footer components)

    Here's a rough visualization of how your project structure would look like