skip to Main Content

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. Can you suggest a way to achieve this?

Note : I am looking for app directory based approach

3

Answers


  1. Referring to my comment on the post, there should be no issue in what you’re trying to do.

    You can create a component called <ParentLayout /> and use it as the layout for problems/react, and use a different component <ChildLayout /> for problems/react/test-problem.

    Import the appropriate components into the respective files, and use them.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. in Next 13 you can use the usePathname hook to determine which page you are on and then logically show or hide it: https://beta.nextjs.org/docs/api-reference/use-pathname

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search