0

Imagine I have an app directory, inside which there are page.tsx and layout.tsx files. I have set a header and footer in layout.tsx which will be shown on every route and between them there is

<main>{children}</main>

But just for the home page ("/" route) I want to display a div "before" the header. I don't want this div to be displayed on other routes like /about. What should I do? If I put this div inside page.tsx which is located inside app directory, it will be shown between header and footer. And by defining different layouts for other folders inside app directory, I can only add something to the root layout. But what I actually want to do here is subtract something (that div before the header) from root layout for other routes.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • 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) – zain ul din Dec 28 '22 at 23:55

1 Answers1

0

Taking inspiration from @Zain_UI_Din's answer which won't work when using the new /app directory. I believe you can do something similar in layout.tsx, but I think you have to make it a client component because you're using the router.

'use client'; // not sure if needed
import { useRouter } from 'next/router';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();

  return (
    <html lang="en">
      <body>
        {router.pathname === '/' && (
          <div>Home page</div>
        )}
        <header>header content</header>
        <main>{children}</main>
        <footer>footer content</footer>
      </body>
    </html>
  );
}

Alternatively, you could define different layouts for the home page and other pages using route groups, which would allow you to do this.

koolskateguy89
  • 276
  • 1
  • 9
  • Thank you both. Problem solved. Although I had to make some changes to what you suggested. In Nextjs 13, there is no pathname like so. We need to use usePathname with must be imported from next/navigation. I declared a const like this: const pathname = usePathname() and use the rest of the code you suggested and it worked. One more thing, I had to use "use client" at the top. – Mostafa Dec 30 '22 at 04:37