skip to Main Content

Is there an implementation of router Outlet in next.js or similar ? I want to render child components on the same page using sub-routes, but I haven’t been able to find anything for next.js that does the same.

2

Answers


  1. you can use something like this,

    app/layout.js

    // - Applies to all routes
    export default function RootLayout({ children }) {
      return (
        <html>
          <body>
            <Header />
            {children}
            <Footer />
          </body>
        </html>
      );
    }
    

    app/dashboard/layout.js

    // - Applies to route segments in app/dashboard/*
    export default function DashboardLayout({ children }) {
      return (
        <>
          <DashboardSidebar />
          {children}
        </>
      );
    }```
    
    refer this,
    
    [enter link description here][1][2]
    
    
      [1]: https://nextjs.org/blog/layouts-rfc
      [2]: https://www.youtube.com/watch?v=69-mnojSa0M
    
    Login or Signup to reply.
  2. Since you’re not using Next.js 13+’s "app directory" there is no native way of handling templates/layouts. Instead you have to create your own layout system

    Here’s an example:

    // /components/Layout.js
    export default function Layout() {
      return (
        <main>
            <header>My Website</header>
            <article>{children}</article>
                    {/*  ^ this is your "<Outlet>" */}
        </main>
      )
    }
    
    // /pages/blog/post1.jsx
    import { Layout } from "@components/Layout";
    
    export default function BlogPost1() {
      return (
        <Layout>
            <h1>Blog post 1!</h1>
        </Layout>
      )
    }
    
    // /pages/blog/post2.jsx
    import { Layout } from "@components/Layout";
    
    export default function BlogPost2() {
      return (
        <Layout>
            <h1>Blog post 2!</h1>
        </Layout>
      )
    }
    

    Don’t take this example literally, in a real-world scenario you would use dynamic router like [id].js.

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