Kodokon kodokon.com

Composition: children and splitting into components

Build reusable container components with the children prop and split your screens into clear responsibilities.

6 min · 3 questions

Open this lesson in Kodokon

Some components do not know their content in advance: a card, a modal window, a layout. React solves this with the special children prop: everything you place between a component's opening and closing tags is handed to it, ready to be inserted wherever it wants. The container handles the frame, the caller supplies the content.

JSX
function Card({ children }) {
  return <section className="card">{children}</section>;
}

function App() {
  return (
    <Card>
      <h2>Invoice #1024</h2>
      <p>Amount: €49.90</p>
    </Card>
  );
}
Card frames any content without knowing what it is.

When a single slot is not enough, pass JSX through named props: a title, a footer, an action bar. A prop can receive a React element just like any other value. You get several “slots”, each one clearly named.

JSX
function Modal({ title, footer, children }) {
  return (
    <div className="modal">
      <header>{title}</header>
      <div className="modal-body">{children}</div>
      <footer>{footer}</footer>
    </div>
  );
}
Three distinct slots: title, children, and footer.

Composition also guides splitting. A component should have one identifiable responsibility: displaying a user row, laying out a list. As soon as a component accumulates several roles, extract sub-components: each one becomes shorter, easier to test, and reusable elsewhere.

JSX
function UserList({ users }) {
  return (
    <ul>
      {users.map((user) => (
        <UserRow key={user.id} user={user} />
      ))}
    </ul>
  );
}

function UserRow({ user }) {
  return (
    <li>
      <strong>{user.name}</strong> - {user.email}
    </li>
  );
}
Each component keeps a single responsibility.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What does a component's children prop receive?
    • The list of its child components declared in the same file
    • Everything placed between its opening and closing tags
    • The props passed down by the parent component
  2. Can you pass JSX in a prop other than children?
    • Yes, a React element is a value like any other
    • No, only the children prop accepts JSX
    • Yes, but only as a string containing HTML
  3. Which signal most reliably indicates that a component should be split?
    • It exceeds twenty lines of code
    • It uses more than one useState
    • It combines several distinct responsibilities in its render