DEV Community

JM
JM

Posted on

πŸš€ Transform Your UI: Creating Layouts Using Compound Components in React – A Step-by-Step Guide

Introduction

Building robust and maintainable layouts can be a challenge in React applications. Compound components offer a way to achieve this by allowing for reusable and modular code. In this tutorial, you'll learn how to create a layout using compound components step by step by leveraging the concept of slots.

The Goal

const App = () => {
  return (
    <MainLayout.Root>
      <MainLayout.Sidebar className="shadow-xl z-10 relative">
        <p>Sidebar</p>
      </MainLayout.Sidebar>
      <MainLayout.Header>
        <h1 className="text-xl font-bold">My App</h1>
      </MainLayout.Header>
      <MainLayout.Body>
        <p>Body</p>
      </MainLayout.Body>
      <MainLayout.Footer>
        <p>Footer</p>
      </MainLayout.Footer>
    </MainLayout.Root>
  );
};
Enter fullscreen mode Exit fullscreen mode

Why Slots?

Before diving into the code, it's crucial to understand what slots are and why we're using them. A slot is just a placeholder where other components can be inserted.

For our layouts we'll be defining two types of slots: a fragment slot and a container slot. The fragment slot prevents the caller from setting any properties, such as className, whereas the container slot allows it. This flexibility lets us control how our layout behaves and is customized.

Create a Fragment Slot

The fragment slot is a simple wrapper that renders its children without adding any additional HTML tags or properties. This kind of slot is beneficial when you want to maintain a clean and controlled structure.

export const Slot = () => (props: { children: React.ReactNode }) => {
  return <>{props.children}</>;
};
Enter fullscreen mode Exit fullscreen mode

Create a Container Slot

The container slot is more versatile and can behave like any HTML tag, such as a div, section, header, etc. This allows for more customization and control. We define a className argument so that we can provide some default classes.

export const ContainerSlot =
  (ar?: {
    as?: "div" | "section" | "header" | "footer" | "main";
    className?: string;
  }) =>
  (props: { children: React.ReactNode } & HTMLProps<HTMLDivElement>) => {
    const El = ar?.as ?? "div";
    return (
      <El {...props} className={cn(ar?.className, props.className)}>
        {props.children}
      </El>
    );
  };
Enter fullscreen mode Exit fullscreen mode

These two slots are the only ones we need for our example but we've also found it useful to create other slots like a "Text" slot that required props.children to be a string.

Getting our slot content

In order to get our slot content when we're defining our layout we need to loop through our props.children using something like React.Children.map but for convenience we'll just use a library react-nanny. You can leave this out if you don't want another dependency.

import { getChildrenByType } from "react-nanny";

export const getSlotByType = (
  children: React.ReactNode | undefined | null,
  type: React.ElementType | React.ElementType[]
) => {
  if (!children) return null;
  const content = getChildrenByType(children, type);
  return content;
};
Enter fullscreen mode Exit fullscreen mode

Define our layout

Let's define our layout sections and layout. We'll create slots for a sidebar, header, footer, and main content area.

const Sidebar = ContainerSlot({
  className: "bg-gray-100 w-64 flex flex-col overflow-hidden",
});

const Header = ContainerSlot({
  className: "bg-gray-100 flex items-center justify-between px-4 py-2",
  as: "header",
});

const Footer = ContainerSlot({
  className: "bg-gray-100 flex items-center justify-between px-4 py-2",
  as: "footer",
});

const Body = ContainerSlot({
  className: "flex-1 overflow-auto",
  as: "main",
});

const Root = (props: { children: React.ReactNode }) => {
  // Here we're using our util to get the appropriate slot content
  const sidebar = getSlotByType(props.children, Sidebar);
  const header = getSlotByType(props.children, Header);
  const footer = getSlotByType(props.children, Footer);
  const body = getSlotByType(props.children, Body);

  return (
    <div className="flex flex-col h-screen w-screen">
      {header}
      <div className="flex flex-1">
        {sidebar}
        {body}
      </div>
      {footer}
    </div>
  );
};

export const MainLayout = {
  Root,
  Sidebar,
  Header,
  Footer,
  Body,
};
Enter fullscreen mode Exit fullscreen mode

Use the layout

We can now use the layout in our application

const App = () => {
  return (
    <MainLayout.Root>
      <MainLayout.Sidebar>
        <p>Sidebar</p>
      </MainLayout.Sidebar>
      <MainLayout.Header>
        <h1 className="text-xl font-bold">My App</h1>
      </MainLayout.Header>
      <MainLayout.Body>
        <p>Body</p>
      </MainLayout.Body>
      <MainLayout.Footer>
        <p>Footer</p>
      </MainLayout.Footer>
    </MainLayout.Root>
  );
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's it! We've created a reusable layout using compound components. Feel free to explore these concepts further and adapt them to your specific needs.

Top comments (0)