Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to achieve outlets in next.js ? in regular react router i could use <outlet> to render child components

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.

like image 278
lams Avatar asked Jan 21 '26 14:01

lams


2 Answers

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.

like image 179
Asplund Avatar answered Jan 25 '26 10:01

Asplund


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}
    </>
  );
}

If you want to know more, refer this:

  • https://nextjs.org/blog/layouts-rfc
  • https://www.youtube.com/watch?v=69-mnojSa0M
like image 34
Sanu Kumar Avatar answered Jan 25 '26 12:01

Sanu Kumar