Next js

Layouts and Components In Next Js

What Are Components?

  • Components are the building blocks of React apps.

  • They are reusable pieces of UI, usually defined as functions or classes.

  • Components help keep your code modular and manageable.


What Are Layouts?

  • Layouts are special components used to define common UI structures (like headers, footers, navigation) shared across multiple pages.

  • They help avoid repetition by wrapping page content with consistent UI elements.


How to Use Components in Next.js

Create a reusable component:

jsx
// components/Navbar.js
export default function Navbar() {
return (
<nav>
<a href="/">Home</a> | <a href="/about">About</a>
</nav>
);
}

Use it in a page:

jsx
// pages/index.js
import Navbar from '../components/Navbar';

export default function Home() {
return (
<>
<Navbar />
<h1>Welcome to the Home Page</h1>
</>
);
}


Creating a Layout Component

Example of a basic layout wrapping children content:

jsx
// components/Layout.js
import Navbar from './Navbar';

export default function Layout({ children }) {
return (
<>
<Navbar />
<main>{children}</main>
<footer>© 2025 My Website</footer>
</>
);
}

Use the layout in a page:

jsx
// pages/about.js
import Layout from '../components/Layout';

export default function About() {
return (
<Layout>
<h1>About Us</h1>
<p>This is the about page content.</p>
</Layout>
);
}


Applying Layout Globally Using _app.js

To avoid importing layout in every page, wrap all pages globally:

jsx
// pages/_app.js
import Layout from '../components/Layout';

export default function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}

Now, every page automatically uses the Layout.


Summary

Concept Purpose
Component Reusable UI pieces for buttons, forms, etc.
Layout Shared page structure (header, footer, nav)
_app.js Wrap pages globally with layouts or providers

Leave a Reply

Your email address will not be published. Required fields are marked *