Blog>
Snippets

Enhancing Page Composability with Layout Components

Demonstrate how to create a consistent layout structure across different pages in Next.js 14, using a custom `Layout` component that wraps page content.
import { ReactNode } from 'react';

interface LayoutProps {
    children: ReactNode;
}

export function Layout({ children }: LayoutProps) {
    return (
        <div className='container'>
            <header>
                {/* Header Content */}
                <nav>
                    {/* Navigation Menu */}
                </nav>
            </header>
            <main>
                {children}
            </main>
            <footer>
                {/* Footer Content */}
            </footer>
        </div>
    );
}
This piece of code defines a functional Layout component using TypeScript in a Next.js application. The component expects a children prop, which will be the content of the current page. The layout includes a header with navigation, a main section where the children prop is rendered, and a footer.
import { Layout } from '../components/Layout';

export default function HomePage() {
    return (
        <Layout>
            <h1>Welcome to the Home Page</h1>
            {/* Rest of the home page content */}
        </Layout>
    );
}
This code snippet shows how a page called HomePage uses the Layout component. By wrapping the page's content within the Layout component, we create a consistent structure across different pages.
import { Layout } from '../components/Layout';

export default function AboutPage() {
    return (
        <Layout>
            <h1>About Us</h1>
            {/* Rest of the about page content */}
        </Layout>
    );
}
Similarly, this snippet demonstrates an AboutPage component that also utilizes the shared Layout component, maintaining consistent styling and structure. Each page is simply wrapped with the Layout to include the header, navigation, and footer components.