SIGN IN

Building React Components Using Children Props and Context API

Stay Informed

It's important to keep up
with indusctry - subscribe!

Stay Informed

Looks good!
Please enter correct name
Please enter correct email
Looks good!
artwork depicting stylized React components

Building better React apps

React provides a number of powerful patterns to compose components; for example, Containment, Specialization, and Render Props. Today we’ll dive into the Containment pattern which, on the surface, looks like an easy-to-understand interface — but the example provided in React docs doesn’t have an explicit explanation of how to pass data from the parent container to its children. Who knows — this very well may help you when cracking React interview questions!

Here is a code snippet from React docs example to refresh your memory:

Let’s try to pass “color” prop from the FancyBorder component to its children.

At first glance, it’s not obvious. The only thing we see in the markup of the example is {props.children} that looks like an opaque prop. Working with it doesn’t look straightforward either. But here comes React.Children to rescue; React docs provide a special section for it.

React.Children

What we need first is React.Children.map(children) to always handle children as an array because when there is only one component, it will not be an array by default. Next thing that we should use is React.cloneElement(element, props) that is used to work around the fact that all React elements are immutable. Finally, we might come up with the following code:

Now every child inside the FancyBorder receives the “color” prop passed down from the parent component. You might admit that, instead of passing down “color” prop from the FancyBorder parent component to all of its children, we could simply add “color” at the top level. That is correct. But there are cases when we can leverage Parent props: for example, when we need to calculate child props based on the parent props.

For example, we could have a Theme component that only takes a “type” name as a prop and provides some specific styling based on this type for all of its children.

Theming with React.Children

Let’s consider the following code:

Every child in this example has a color and background based on the “type” prop of the parent. Besides that, the code is easy to reuse: just wrap the Theme component around any children and they become “themed”.

React.Children toggler

“Just wrap and it works” pattern with zero configuration is so cool that I would like to build a component that has dynamic state passed to children. Is it possible? Can we have a simple interface that allows toggling content on a button click with the following markup, seen in the code below?

Unbelievable, but yes, we can. Here is the code:

The code in this example considers that toggler button is the first element inside a wrapper. You can change the order of elements and still have a toggle functionality if you verify toggler by some specific element prop like “type” or “isToggler”. Then you should check el.props.type instead of index in renderChildren function. In case of the content, we don’t need element cloning, as soon as no modifications are needed, so the code just renders the element or returns null.

In this example, I also use React Hooks API (here’s a great article about using React Hooks with RxJS) to showcase how to change the state of the component, but you could also use regular class component for that purpose as well.

Full code with comments on GitHub

Live example with code on CodeSandbox

React parent container

The simplicity of the Toggler example above has a limitation: button and content should be immediate children of the Toggler component. That is probably an option in many cases, but should we just give up in case there is some nesting? The answer is: we can work around nesting, but nothing comes without tradeoffs, so we should add some extra markup.

Let’s add some nesting to reproduce the issue with simple React.Children approach. Also, we should wrap each child that is related to Toggler in a sub-component (I will explain the reason for it a bit later). Please check the following markup:

To achieve the goal of toggling the Content with click on the Trigger, Toggler.Trigger and Toggler.Content sub-components should share state with their parent Toggler. In this case, multiple other benefits are gained:

  • The order might be different.
  • There could be multiple Toggler.Content as well as multiple Toggler.Trigger components.
  • The level of nesting also doesn’t matter.
  • We could add any amount of extra markup, but it’ll still work.

And that all is possible thanks to React.Context API.

React.Children and React.Context

Let’s check the code for the React.Children + React.Context toggler implementation:

The code above is a pretty standard React class implementation with a few lines that probably need a bit of explanation:

  1. First of all, take a look at Context.Provider. It is passing isVisible prop and setVisible function down to all of the Context.Consumers.
  2. There are 2 Context.Consumers in the code: Toggler.Trigger and Toggler.Content that are implemented as static fields of the Toggler class.
  3. addPropsToChildren is a simple helper that adds any props to children passed.

artwork depicting React context provider

Props merging

In a real-world app, there could be a case when there is a need to call some Content function and hide Content after that. React.cloneElement replaces the prop completely, so if we want to have both functions called while working with Content, we should merge them. Let’s look at one example:

The Content static field of the class might look like this:

The code above replaces the onClick prop of the child component with a new function that will execute both the original callback of the element as well as the setVisible function of the class that is used to toggle visibility of the element. This way any prop of a child might be modified.

Real World example

As a real-world example, let’s take ant-design Modal component to show how it can be integrated with a Toggler component written using React.Children and React.Context composition pattern.

There are at least 3 props that are commonly used in Modal: onOk, onCancel, and visibility, but in the markup example above we only need the onOk handler; the rest of the implementation might be hidden. Here is a code snippet with props merging function example that works under the hood:

As you can see, the onOk handler needs merging, while visible and onCancel props are just passed from parent context. In this code el is the currently cloned React.Children item while context is React.Context. I omit the rest of the implementation to not repeat myself as soon as everything else was already mentioned in the article text above. But in case you are curious about the details, please feel free to check out the code on GitHub, or live code on CodeSandbox.

Live code on CodeSandbox

Full code on GitHub with comments

React live demo on CodeSandBox

Summary

To sum up the above: using Containment composition with React.Children and React.Context is a very powerful pattern that works like a zero configuration “just wrap and it works” approach. You can build reusable components on top of it that encapsulate all implementation details but still provide a lot of flexibility. I hope you enjoy it!

artwork depicting React Children Cheat Sheet

About the author

Stay Informed

It's important to keep up
with indusctry - subscribe!

Stay Informed

Looks good!
Please enter correct name
Please enter correct email
Looks good!

Related articles

11.09.2019

Responsible Web Scraping: Gathering Data Ethically and Legally

In this article, we’ll explore the definition of web scraping, how it works, its use cases, legal and ethical issues — and how to avoid them by>>>

JavaScript

Implementing Role-Based Access Control in a Node.js application

In this article, you'll learn how to implement role-based access control in a Node.js>>>

JavaScript

Contentful+Gatsby = Smarter content management

In this article, we'll explain how to integrate Contentful, a CMS with a blog built with Gatsby, a fast framework based on>>>

JavaScript

4 comments

Kirill Novik August 28, 2019 at 10:31 am
0

Great stuff, very useful pattern! But I think the title of the article is misleading, I think it should explicitly mention “Containment pattern” in the title.

 
Alexander Solovyev August 27, 2019 at 10:51 pm
0

Thanks for your comment, Kirill! Yes, “naming things is hard” and having a “Containment…” in a heading sounds like a good idea

ahmed ayoub September 6, 2019 at 12:56 pm
0

Nice and useful reading.

one typo in “Theming with React.Children” section code at line 2 it should be `const style = props.type === “day” not const style = props.theme === “day”

Also sent you couple of PRs to simplify the code a bit if you don’t mind.

 
Alexander Solovyev August 27, 2019 at 3:51 pm
0

Thanks, Ahmed! Very good points, I have merged your PRs, so the demos should now be updated. Article code was updated accordingly

Sign in

Forgot password?

Do not have account yet? You can create one

Or use a social network account

 

By clicking Sign Up, you agree to our privacy policy

Sign up

Already have an account? Please

Or use a social network account

 

By clicking Sign Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By clicking Sign Up, you agree to our privacy policy