Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js 13: Customizing Next.js layouts based on route hierarchy

I am working on a Next.js 13 project where I have a route named problems/[slug]. On the first level of this route (e.g., problems/react), I have a sidebar and a content section, which I am displaying using a layout.tsx.

However, on the next nested level of the route (e.g., /problems/react/test-problem), I want to use a different layout instead of the original one. Is there a way to achieve this?

Note: I am looking for an app directory-based approach

like image 685
NIsham Mahsin Avatar asked Oct 24 '25 16:10

NIsham Mahsin


2 Answers

In Next.js 13, you can use the usePathname hook to determine which page you are on and then logically show or hide it:

const pathname = usePathname(); const show_Navbar_Sidebar = pathname === '/about' || pathname === '/signup' ? false : true;

like image 117
Mohammed Al Safadi Avatar answered Oct 27 '25 06:10

Mohammed Al Safadi


You can keep the structure of the pages folder as shown below

pages/
    problems/
      [slug]/
        - index.js      // will match for /problems/[:slug] 
        - [problem].js   // will match for /problems/[:slug]/[:problem]

If you need multiple layouts, you can add a property getLayout to your page, allowing you to return a React component for the layout. This allows you to define the layout on a per-page basis. Since we're returning a function, we can have complex nested layouts if desired.

// pages/problems/[slug]/index.js

import StandardLayout from '../components/StandardLayout'

export default function ProblemMainPage() {
  return (
    /** Your content */
  )
}

ProblemMainPage.getLayout = function getLayout(page) {
  return (
    <StandardLayout>
      {page}
    </StandardLayout>
  )
}
// pages/problems/[slug]/[problem].js

import AnotherLayout from '../components/AnotherLayout'

export default function ProblemDetail() {
  return (
    /** Your content */
  )
}

ProblemDetail.getLayout = function getLayout(page) {
  return (
    <AnotherLayout>
      {page}
    </AnotherLayout>
  )
}

Update your pages/_app.js file

// pages/_app.js

export default function MyApp({ Component, pageProps }) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout || ((page) => page)

  return getLayout(<Component {...pageProps} />)
}

Learn more about it on Next.js documentation here

like image 27
Nikhil Chauhan Avatar answered Oct 27 '25 07:10

Nikhil Chauhan