Skip to main content

Welcome to a Grasp lesson

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

Lesson 12

Building Flexible Wrappers with `children`

Recommended resources

Hello! Let's get started on our next lesson.

Introduction

In our last lesson, we focused on making our components more robust by defining default values for optional props. We saw how using modern JavaScript default parameters (({ prop = 'default' })) provides a clean and predictable way to handle missing data.

So far, we've passed data into components as named attributes, like <UserProfileCard name="Satoshi" />. But what happens when we want to pass a whole block of content, maybe including other components, into a component? This is a fundamental pattern in building UIs, just like nesting tags in HTML (<div><p>Some text</p></div>).

Today, we'll explore React's powerful solution for this: the special children prop. Our learning outcome is to use the children prop to create flexible, reusable wrapper components. This concept is the cornerstone of component composition, a key principle for writing clean, scalable, and maintainable React applications.


The children Prop: React's Nesting Mechanism

In HTML, you intuitively nest elements inside one another. The outer element "wraps" the inner elements. React components can do the exact same thing.

When you place content between the opening and closing tags of a component, React automatically collects that content and makes it available inside your component via a special prop called children.

Understanding React's `props.children`
This diagram illustrates how content (in this case, an `<h1>` and a `<p>` tag) placed between a component's tags is passed into that component and can be rendered using `props.children`.

This allows a parent component to define its structure without needing to know the specific content that will be placed inside it.

To get a clear, practical demonstration of this concept, let's watch a short video.

React - Nested Components Tutorial (Childen props)

This video from Austin Davis provides a fantastic introduction to nested components and the children prop. It clearly explains why this is more flexible than hardcoding content inside a component.

Please watch from the beginning until 03:08. Pay close attention to: The problem with hardcoding child components. How to access and render {children} inside a wrapper component. The special syntax of placing content between the component's tags instead of passing a named prop.

As the video demonstrated, the mechanics are straightforward:

  1. In your wrapper component (e.g., CardSection), accept children as a prop and render it inside your JSX: {children}.
  2. When you use that component, switch to an opening/closing tag syntax (<CardSection>...</CardSection>) and place whatever you want to render inside.

Building Reusable Wrapper Components

The primary use case for children is creating wrapper components. These are components that provide a consistent structure, style, or functionality around arbitrary content. A Card, Modal, or PageLayout are all classic examples.

This pattern is fundamental to the software engineering principle of composition over inheritance, and it helps keep your codebase DRY (Don't Repeat Yourself). Instead of creating dozens of slightly different components (CardWithImage, CardWithForm, CardWithFooter), you create one flexible Card component and compose different content inside it.

The Children Prop: React's Secret to Reusable Wrapper Components

Let's read a short article that provides a great example of building a Card wrapper and explains the 'why' behind this pattern.

Please read the sections "Building Your First Wrapper: A Card Component" and "Composition vs. Copy-Paste". Notice how a single Card component can be used for vastly different content without any changes to its own code.

Here’s a simple Card component based on that idea:

// Card.tsx
import React from 'react';

// We'll add proper typing in the next step!
const Card = ({ children, title }: { children: any; title?: string }) => {
  const cardStyle: React.CSSProperties = {
    border: '1px solid #ddd',
    borderRadius: '8px',
    padding: '16px',
    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
    maxWidth: '400px',
    margin: '1rem',
  };

  return (
    <div style={cardStyle}>
      {title && <h3 style={{ marginTop: 0 }}>{title}</h3>}
      {children}
    </div>
  );
};

// App.tsx
const App = () => {
  return (
    <div>
      <Card title="User Profile">
        <p>Name: Kenji Tanaka</p>
        <p>Role: Software Engineer</p>
      </Card>

      <Card title="Image Post">
        <img src="https://via.placeholder.com/350x150" alt="Placeholder" style={{ maxWidth: '100%' }} />
        <p>A placeholder image in a card.</p>
      </Card>
    </div>
  );
};

The Card component provides the styling and structure, but it remains completely agnostic about the content it holds. This is the power of composition.


Typing children with TypeScript

As you saw in the code above, I used any as a placeholder for the children type. This is bad practice, and we can do much better. So, what is the correct type for children?

React provides a utility type called React.ReactNode. A ReactNode can be:

  • A JSX element (<div>, <MyComponent />)
  • A string or a number
  • An array of ReactNodes
  • A boolean, null, or undefined (which are not rendered)
  • A React Fragment

To make typing wrapper components easier, React provides a generic type helper: PropsWithChildren. It takes your component's own props type and adds the children prop to it for you.

PropsWithChildren Type Composition
This diagram shows that `PropsWithChildren<FooProps>` is a type that combines your custom `FooProps` with the `children` prop, which is typed as `ReactNode`.

Let's refactor our Card component to use PropsWithChildren.

Clean React with TypeScript

This article from weser.io provides a concise and clean explanation of how to use PropsWithChildren for correct typing.

Read the section titled 'Children'. Note how PropsWithChildren is a generic that wraps your existing props type.

Here's the updated, type-safe Card component:

import React, { PropsWithChildren } from 'react';

// 1. Define the component's own props
interface CardProps {
  title?: string;
}

// 2. Use PropsWithChildren<CardProps> as the type
const Card = ({ children, title }: PropsWithChildren<CardProps>) => {
  // ... same styling and return statement as before
  const cardStyle: React.CSSProperties = {
    border: '1px solid #ddd',
    borderRadius: '8px',
    padding: '16px',
    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
    maxWidth: '400px',
    margin: '1rem',
  };

  return (
    <div style={cardStyle}>
      {title && <h3 style={{ marginTop: 0 }}>{title}</h3>}
      {children}
    </div>
  );
};

Now our component is fully type-safe. The children prop is correctly typed as an optional React.ReactNode, and we can destructure it alongside our own title prop.

Test your understanding!

Create a Modal component that acts as a wrapper. It should:

  1. Have a semi-transparent backdrop and a centered white content box.
  2. Accept a title string prop to display at the top of the modal.
  3. Render any children passed to it inside the content box.
  4. Use PropsWithChildren for correct TypeScript typing.

Don't worry about the logic to open/close the modal; just focus on its structure as a wrapper.

Show answer

Here's a possible implementation for the Modal component:

// Modal.tsx
import React, { PropsWithChildren } from 'react';

interface ModalProps {
  title: string;
}

const Modal = ({ title, children }: PropsWithChildren<ModalProps>) => {
  const backdropStyle: React.CSSProperties = {
    position: 'fixed',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  };

  const modalStyle: React.CSSProperties = {
    backgroundColor: 'white',
    padding: '20px',
    borderRadius: '8px',
    width: '500px',
    maxWidth: '90%',
  };

  return (
    <div style={backdropStyle}>
      <div style={modalStyle}>
        <h2>{title}</h2>
        <hr />
        {children}
      </div>
    </div>
  );
};

// Example Usage in App.tsx
const App = () => {
    return (
        <Modal title="Terms of Service">
            <p>This is the content of the modal. You can put anything here, from simple text to complex forms or other components.</p>
            <button>I Agree</button>
        </Modal>
    );
};

export default App;

Advanced Composition Patterns

Your strong background in TypeScript and software development allows us to explore some more advanced and powerful patterns.

1. Wrapping Native HTML Elements

What if you want to create a custom <Button> component that adds specific styling but should still accept all the standard HTML button props like onClick, disabled, type, etc.? Manually adding every prop to your interface would be tedious and error-prone.

Instead, you can extend React's built-in types for HTML elements.

React TypeScript Tutorial - 22 - Wrapping HTML Elements

The Codevolution channel has an excellent, concise video on this exact topic. It shows how to use React.ComponentProps to create type-safe wrappers for native HTML elements.

Watch from 02:45 to 04:31. Focus on how React.ComponentProps<'button'> is used to inherit all the properties of a standard button, including children and event handlers like onClick.

The pattern looks like this:

type CustomButtonProps = {
  variant: 'primary' | 'secondary';
} & React.ComponentProps<'button'>; // Inherit all button props

const CustomButton = ({ children, variant, ...rest }: CustomButtonProps) => {
  // Apply styles based on variant
  // Spread the rest of the props onto the button element
  return (
    <button {...rest}> 
      {children}
    </button>
  );
};

This is an incredibly powerful technique for building design systems and reusable component libraries.

2. Multiple "Slots"

Sometimes, one children prop isn't enough. A layout component might need a sidebar and a mainContent area. In these cases, you can use the children prop for the primary content area and regular props for the other "slots." The type for these additional slots will be React.ReactNode.

import React, { PropsWithChildren, ReactNode } from 'react';

interface TwoColumnLayoutProps {
  sidebar: ReactNode; // A slot for the sidebar content
}

const TwoColumnLayout = ({ sidebar, children }: PropsWithChildren<TwoColumnLayoutProps>) => {
  return (
    <div style={{ display: 'flex' }}>
      <aside style={{ width: '200px', borderRight: '1px solid #ccc' }}>
        {sidebar}
      </aside>
      <main style={{ flex: 1, padding: '1rem' }}>
        {children} {/* The main content goes here */}
      </main>
    </div>
  );
}

This pattern gives you structured, multi-slot components that are still highly flexible.


Conclusion

You have now mastered one of the most fundamental and powerful concepts in React. Wrapper components built with the children prop are the key to creating flexible, reusable, and maintainable UIs.

Key Takeaways:

  • The children prop allows you to pass JSX and other components into a component by nesting them between its opening and closing tags.
  • This pattern is used to create wrapper components (Card, Modal, Layout) that provide structure or style without being coupled to their content.
  • Using composition with children helps you write DRY code and avoids creating many near-identical components.
  • In TypeScript, use the PropsWithChildren<YourProps> generic type to correctly type components that accept children. React.ReactNode is the underlying type for anything React can render.
  • For advanced wrappers around native elements, you can use React.ComponentProps<'element'> to inherit all standard HTML attributes and event handlers.

Next Steps

Now that we understand how to pass data via named props and compose components using children, we're ready to put it all together. In our next lesson, we will focus on how to compose multiple components to build a complex UI hierarchy. We'll see how these individual, flexible building blocks can be assembled to create sophisticated application layouts.