React Children

Image of Author
September 22, 2022 (last updated September 21, 2022)

There are a few "reserved words" in React. One of them is "children" in props.children. The props.children prop is present on every component, whether you use it or not. The children prop is particularly useful for writing composable code. React refers to this type of composition as containment.

Let's look at two ways to achieve containment. The first is what I will call "arbitrary prop containment". The second, "children prop containment".

// arbitrary prop containment

function Parent() {
  const content = <div>This is the content</div>;

  return (
    <div>
      <Child title="This is the title" content={content} />
    </div>
  );
}

function Child({ title, content }) {
  return (
    <div>
      <div>{title}</div>
      {content}
    </div>
  );
}
// children prop containment

function Parent() {
  return (
    <div>
      <Child title="This is the title">
        <div>This is the content</div>
      </Child>
    </div>
  );
}

function Child({ title, children }) {
  return (
    <div>
      <div>{title}</div>
      {children}
    </div>
  );
}

Both examples are successfully rendering the same HTML markup. However, the latter is more idiomatic in React. The reason why is because it is leveraging props.children to nest the content element within the Child component.

You might find yourself in a situation where you want to define variables of React elements and pass them around as arbitrary props. This is not the worst thing in the world. But, I'd encourage you to leverage the benefits of props.children when you can.

  1. It let's you write HTML-like markup with React components
  2. The React library knows you are trying to pass React elements via props.children and can give you more helpful errors/feedback as a result.
  3. You are less likely to misuse props.children, since it is a reserved word in React, when compared with elements passed around as arbitrary props.