Tutorial

Creating Compositional Components in React With this.props.children

Published on August 18, 2017
Default avatar

By William Le

Creating Compositional Components in React With this.props.children

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

If you’re a newcomer to React, you may have seen this.props.children in various tutorials. Sometimes its purpose isn’t clear or you may have thought, “I could have done it a different way.” Let’s find out the unique perks of using children in React so we can feel more confident about when we should be using it.

button children

Basic Usage

Imagine that we need to build a <PrimaryButton/> component for all of the call-to-action buttons in our app.

class PrimaryButton extends React.Component {
  render() {
    return (
      <button onClick={this.props.onClick}>
        {this.props.text}
      </button>
    )
  }
}

//usage
<PrimaryButton text="Getting Started" onClick={this.somehandler} />

Your design team wants to add a small feature: include an icon before the words “Getting Started”. This is where things get interesting…

//refactor
class PrimaryButton extends React.Component {
  render() {
    return (
      <button onClick={this.props.onClick}>
        {this.props.icon}{this.props.text}
      </button>
    )
  }
}

//usage
<PrimaryButton
  icon={IconFile}
  text="Getting Started"
  onClick={this.somehandler}
/>

While this solution is certainly reasonable it creates a tight interface with <PrimaryButton/> because you have to be explicit about the stuff in the button. This can lead to brittle components that easily break when you need to introduce new features. But aha! There’s a more robust solution!

//refactor
class PrimaryButton extends React.Component {
  render() {
    return (
      <!--
      <button onClick={this.props.onClick}>
        {this.props.icon}{this.props.text}
      </button>
      -->
      <button onClick={this.props.onClick}>
        {this.props.children}
      </button>
    )
  }
}

//usage
<PrimaryButton onClick={this.somehandler}>
  <IconFile/> Getting Started
</PrimaryButton>

Notice how unopinionated <PrimaryButton/> is about its content! You could put any valid HTML tags in there, image files, React components… egads you could even reverse the order of the text and icon!

But what’s this weird this.props.children?

this.props.weird

When I first began using React one of the biggest deterrents from embracing this.props.children was because of the odd way it’s used. Wrapping a React component around other React components? Assume all these components are gonna get implicitly passed to the parent? Using a reserved namespace in props to access the… “children”? Super weird.

But just like how weird JSX was initially, once you practice using this.props.children more and get used to the syntax… it’ll become as indispensable as JSX! Identifying places to use parent-children relationships will become more intuitive to you.

children is the only prop that’s not passed via attribute like onClick onChange key or style. Rather, it’s implicitly passed when you wrap it with a React component (considered the “parent” component). The language of “parent” and “child” is from HTML where you have parent and children DOM nodes.

alligator component

Wrapping Up

In the real-world, a React app will have a blend of these wrapper components (the React team calls them compositional components since you compose more sophisticated React components from simpler ones), as well as components that don’t wrap over any React components (see my first code snippet). That’s perfectly normal. As you discover more about your product you’ll be able to identify more redundant UI/UX that can be turned into compositional components.

For example, some good candidates to refactor into composition components are: modals, hovering/clicked styling, notification snackbars, deck slider, etc. It’s really up to your discretion to be as rigorous or loose with this compositional style. The more a React component relies on arbitrary content inside it and some common denominator of UI functionality that’s used app-wide… the more you’ll benefit from using this parent-children pattern.

👉  Checkout the demo on Codepen. Notice how sophisticated features are incrementally layered-on using various composed components.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
William Le

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel