Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 13

Building Complex UIs with Component Composition

Recommended resources

Hello! Welcome to your next lesson on building React applications.

Introduction

In our previous lesson, we explored the children prop, a fundamental mechanism for creating flexible, reusable wrapper components. You learned how to build components like Card and Modal that can contain any content, and how to type them correctly using PropsWithChildren in TypeScript.

So far, we have focused on building and configuring individual components in isolation. The real power of a component-based framework like React, however, comes from combining these individual "building blocks" into larger, more complex structures.

Today, we will focus on exactly that. Our learning outcome is to compose multiple components to build a complex UI hierarchy. We'll move from thinking about single components to visualizing and implementing an entire component tree, which is the skeleton of any React application.


Thinking in Components: Deconstructing a UI

A core skill in React development is the ability to look at a UI design or mockup and break it down into a hierarchy of components. Each component should ideally be responsible for one piece of the UI and be reusable if that piece appears elsewhere. This is analogous to how you might break down a complex system into smaller, more manageable functions or classes in software engineering.

Let's look at a visual example.

React Component Hierarchy for a Contacts Application
This diagram shows a typical component hierarchy for a contact management application. The entire UI is broken down into a tree of nested components.

This diagram illustrates the "thinking in React" process:

  • At the very top, we have the root App component.
  • The App component renders a Contacts component, which acts as the main container for this feature.
  • The Contacts component itself is composed of other components: a SearchBar, an AddContact section, and a ContactList.
  • This decomposition continues down the tree. AddContact contains an AddContactForm, and ContactList is responsible for rendering a list of ContactCard components.

Each box represents a self-contained unit with its own props, state (which we'll cover soon), and markup. By composing them this way, we create a clear structure that is easier to understand, maintain, and debug. The parent-child relationships define how data flows through the application and how components are organized.


Composition in Practice: Assembling a Login Form

Let's put this theory into practice by building a familiar piece of UI: a login form. We will compose it from smaller, more primitive components. This process is very similar to building a UI library or a design system, where you start with atoms (like buttons and inputs) and compose them into molecules (like a form field with a label and input) and then into organisms (the complete login form).

The following video demonstrates building a UI library from scratch. While we won't build the entire library, we'll focus on the final step where individual components are assembled into a complete login form.

Build a UI Library with React, Typescript, TailwindCSS and Storybook

This video from Code With Gionatha shows how to build and compose several components. We'll focus on how layout components (Box, Stack) and UI components (Text, Input, Button) are put together to create a cohesive LoginForm.

Please watch from 00:44:41 to 00:56:21. This segment covers two key parts: Layout Composition (00:44:41 - 00:51:03): Pay attention to how a Stack component is created to arrange items vertically. It's a great example of a specialized layout component built for a specific purpose. UI Assembly (00:51:03 - 00:56:21): This is the main event. Observe how the Box, Stack, Text, Input, and Button components are combined to create the final LoginForm hierarchy. Notice the declarative nature of the JSX.

As you saw in the video, the final LoginForm component is a great example of composition. It doesn't contain complex logic itself; instead, it acts as a composer, arranging other specialized components in a specific hierarchy:

// Simplified structure from the video
<Box> {/* The main container with border and padding */}
  <Stack> {/* Lays out its children vertically */}
    <Text as="h2">Login</Text>
    <Text as="span">Please enter your credentials...</Text>
    
    <Text as="label">Username</Text>
    <Input id="username" />

    <Text as="label">Password</Text>
    <Input id="password" type="password" />

    <Button type="submit">Login</Button>
  </Stack>
</Box>

Each component (Box, Stack, Text, Input, Button) has its own distinct responsibility, props, and styling. By composing them, we build a complex UI from simple, predictable parts. This makes the code readable and easy to modify. For instance, changing the spacing between elements is a simple change within the Stack component, not the LoginForm.


Advanced Composition Patterns

Your background in programming and system design will help you appreciate that there are more structured and powerful ways to handle composition. Let's explore a pattern that leads to highly flexible and descriptive component APIs: Compound Components.

The Problem: The Monolithic Component

Often, a component starts simple but grows in complexity as new requirements are added. A common anti-pattern is to add more and more boolean props to control its behavior (showIcon, iconPosition, allowClose, etc.), leading to a bloated and inflexible component.

Un-Suck Your React Components - Composable & Compound Components

This video from Vincas Stonys clearly illustrates the problem of a single, inflexible component that accumulates too many props.

Watch the first two minutes (00:00:00 - 00:01:54). The video introduces a ProductCard component and shows how adding boolean flags to control its parts quickly becomes unmanageable.

The Solution: The Compound Component Pattern

The compound component pattern solves this by breaking the monolithic component into a set of related components that work together. The main component acts as a parent and provides a "namespace" for its children. A great real-world example is the <select> and <option> tags in HTML. The <option> tag doesn't make much sense on its own; its meaning is derived from being inside a <select>.

Let's see how to refactor the ProductCard into a compound component.

The Future of React: Enhancing Components through Composition Pattern

This article from dev.to, 'The Future of React', provides a great textual explanation of this refactoring process using a CtaButton example. It's a great supplement to the video we're about to watch.

Read the sections 'The Traditional Approach', 'The Composition Pattern', and 'Understanding the Transition'. Notice how the single CtaButton is broken down into Cta.Root, Cta.Icon, and Cta.Text. This is the core idea of the compound component pattern.

Now, let's watch the implementation. The key is to create a main component and then attach its sub-components as properties to it. This provides a clear, discoverable API.

Un-Suck Your React Components - Composable & Compound Components

Continuing with the ProductCard example, this part of the video shows exactly how to implement the compound component pattern.

Watch from 00:12:47 to 00:15:11. Focus on the technique used to create the namespace. Since functions are objects in JavaScript, you can attach other components as properties, like ProductCard.Image = ProductImage;.

The result is a highly declarative and flexible API. Instead of a mess of props:

<ProductCard 
  product={product} 
  showRating={false} 
  showPrice={true} 
  buttonText="View" 
/>

You get a clean, composable structure where the developer has full control over the layout and content:

<ProductCard product={product}>
  <ProductCard.Image />
  <ProductCard.Info>
    <ProductCard.Title />
    <ProductCard.Category />
    {/* No rating rendered, because we simply omit the component */}
    <ProductCard.Price />
  </ProductCard.Info>
  <ProductCard.Button onClick={(p) => console.log(p.name)}>
    View
  </ProductCard.Button>
</ProductCard>

This pattern leverages your knowledge from the previous lesson (children) and combines it with a smart way of organizing and exposing components. It eliminates "prop drilling" for presentational concerns and gives the consumer explicit control over the final output.

Test your understanding!

Imagine you are building a DataTable component. Using the compound component pattern, what might the sub-components be named, and how would you structure the JSX to render a simple table with a header and two rows?

Show answer

Following the compound component pattern, you would likely have sub-components like DataTable.Header, DataTable.Body, DataTable.Row, and DataTable.Cell.

The JSX structure could look something like this:

<DataTable>
  <DataTable.Header>
    <DataTable.Row>
      <DataTable.Cell>Name</DataTable.Cell>
      <DataTable.Cell>Email</DataTable.Cell>
      <DataTable.Cell>Role</DataTable.Cell>
    </DataTable.Row>
  </DataTable.Header>

  <DataTable.Body>
    <DataTable.Row>
      <DataTable.Cell>Rintaro Okabe</DataTable.Cell>
      <DataTable.Cell>okabe@futuregadgetlab.com</DataTable.Cell>
      <DataTable.Cell>Lead Scientist</DataTable.Cell>
    </DataTable.Row>
    <DataTable.Row>
      <DataTable.Cell>Kurisu Makise</DataTable.Cell>
      <DataTable.Cell>makise@vtu.edu</DataTable.Cell>
      <DataTable.Cell>Neuroscientist</DataTable.Cell>
    </DataTable.Row>
  </DataTable.Body>
</DataTable>

This API is very expressive and mirrors the structure of an HTML <table> element, making it intuitive to use.


Conclusion

In this lesson, we elevated our understanding from creating single, flexible components to composing them into complex and meaningful UI hierarchies.

Key Takeaways:

  • Component-Based Thinking: The first step in building a React UI is to mentally decompose the design into a tree of components, each with a single responsibility.
  • Composition in Practice: You build complex UIs by nesting components. Layout components (Stack, Grid) are crucial for arranging other components.
  • Declarative UIs: Composition results in a declarative code style where the JSX structure closely mirrors the visual structure of the UI, making it easy to read and understand.
  • Compound Components: This advanced pattern provides a powerful way to create flexible and expressive APIs by grouping related components under a single namespace (e.g., Card.Header, Card.Body). It gives the consumer maximum control over structure and content while avoiding prop-drilling.

Next Steps

We've now established how to build a static UI hierarchy and pass data down from parent to child. But what happens when a child component needs to communicate back up to its parent? For example, how does the LoginForm know when the user types in the Input component?

In our next lesson, we will tackle this exact problem by learning how to pass functions as props to enable child-to-parent communication. This will be our first step into making our applications interactive.