Next.js: A Practical Introduction for Developers

Advanced Component Patterns: Composition and Slots

Section 7

Styling and Components: Building User Interfaces

Next.js: A Practical Introduction for DevelopersStyling and Components: Building User Interfaces

As we build more complex user interfaces in Next.js, mastering component patterns becomes crucial for creating maintainable, scalable, and reusable code. Two powerful patterns that stand out are Composition and Slots. These techniques allow us to build flexible components by defining how they can be extended and customized by their parent components.

Composition is the fundamental principle of building complex components by combining simpler, independent components. Instead of creating one monolithic component, we break it down into smaller, focused pieces that can be reused and assembled in various ways. This aligns perfectly with the React component model.

Consider a Card component. A card might typically contain a header, a body, and a footer. Instead of hardcoding these sections within the Card component itself, we can design it to accept them as children.

function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}

function CardHeader({ children }) {
  return <div className="card-header">{children}</div>;
}

function CardBody({ children }) {
  return <div className="card-body">{children}</div>;
}

function CardFooter({ children }) {
  return <div className="card-footer">{children}</div>;
}

// Usage
<Card>
  <CardHeader>Card Title</CardHeader>
  <CardBody>
    <p>This is the content of the card.</p>
  </CardBody>
  <CardFooter>Read More</CardFooter>
</Card>

In this example, the Card component doesn't know or care about the specific content of its header, body, or footer. It simply renders whatever is passed to it via the children prop. This makes the Card component highly reusable and adaptable.

graph TD;
    Card --> CardHeader;
    Card --> CardBody;
    Card --> CardFooter;
チャプターへ戻る