Nolan Phillips
Nolan Phillips's Blog

Nolan Phillips's Blog

The React Named Children Pattern

Passing multiple children in React often leads to awkward APIs. That’s where the Named Children Pattern can help.

Nolan Phillips's photo
Nolan Phillips
·Aug 12, 2020·

2 min read

Composition

One of the key concepts of React development is composition

Composition is all about making BigThings by combining many SmallThings together.

Let’s look at a few ways to do this.

The Children Pattern

The simplest technique we have is The Children Pattern. It is the first pattern you learn in the React documentation.

If we wanted to render the text Hello World inside of a <Card> component we would like do it this way:

<Card>Hello World</Card>

The Children Pattern is about displaying content, but sometimes there are other messages we want to send our component.

If we're looking to make our <Card> component larger, we might tell it that via the size prop.

<Card size="large">Hello World</Card>

This pattern works if <Card> has just one content section but not if it has many.

The Props-Children Pattern

When we have many children, The Props-Children Pattern can be useful.

Instead of passing our text in via children we pass it as a prop:

<Card
  size="large"

  title="Hello World"
  subtitle="This is a basic example"
  body="Here is where a lot more text would go."
/>

Unfortunately this makes unfamiliar components harder to understand since its props might set its appearance OR its content.

It also becomes super ugly when the content is not just plain text:

<Card
  size="large"
  title="Hello World"
  subtitle={
    <>
      This is a basic <strong>example</strong>
    </>
  }
  body="Here is where a lot more text would go."
/>

The Named Children Pattern

The Named Children pattern helps with both the mixing of concerns and (subjectively) the ugliness.

React's children does not need to be a component or even a string, it can be a Plain Old Javascript Object. Because of this we pass children an object that maps section names too different content.

<Card size="large">
{{
  title: "Hello World"
  subtitle: <>This is a basic <strong>example</strong></>
  body: "Here is where a lot more text would go."
}}
</Card>

This approach separates content from config making it easier to know whether the prop is for changing its appearance or its content.

Implementing the Named Children Pattern

The Named Children Pattern must be hard to implement, right?

Nope! Although children are set differently outside of the component, inside they're treated like any other prop:

function Card({ size = "medium", children }) {
  return (
    <div className={size}>
      <h2>{children.title}</h2>
      <h3>{children.subtitle}</h3>
      <p>{children.body</p>
    </div>
  )
}

The Named Children pattern is a promising approach to separating concerns in React Components making them easier to read and easier to change.

 
Share this