Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Tempor Nec Feugiat Nislpretium Fusce Platea Dictumst

    Startups

    Conquering Imposter Syndrome: Empowering Startup Founders

    JavaScript

    Getting started with Next.js

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Building React Components Using Children Props and Context API
    JavaScript

    Building React Components Using Children Props and Context API

    Alexander SolovyevBy Alexander SolovyevAugust 22, 2019Updated:August 27, 2019No Comments8 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Building React Components Using Children Props and Context API
    Building better React apps
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    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:

    function FancyBorder(props) {
      return (
        <div className={'FancyBorder FancyBorder-' + props.color}>
          {props.children}
        </div>
      );
    }
    function WelcomeDialog() {
      return (
        <FancyBorder color="blue">
          <h1 className="Dialog-title">
            Welcome
          </h1>
          <p className="Dialog-message">
            Thank you for visiting our spacecraft!
          </p>
        </FancyBorder>
      );
    }
    

    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:

    const FancyBorder = ({ children, color }) => {
      const childrenWithProps = React.Children.map(children, element =>
        React.cloneElement(element, { style: { color } })
      );
     
      return (
         <div className={'FancyBorder FancyBorder-' + props.color}>
              {childrenWithProps}
         </div>;
    }
    

    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:

    const Theme = ({ children, type }) => {
      const style = type === "day" 
          ? { color: "black", background: "white" } 
          : { color: "white", background: "black" }
      const themedChildren = React.Children.map(children, element =>
        React.cloneElement(element, { style })
      );
     
      return themedChildren;
    }
     
    <Theme type="day">
         <h1>Welcome!</h1>
         <div>Some text inside</div>
    </Theme>
    

    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?

    <Toggler>
      <button>toggle</button>
      <div>Content</div>
    </Toggler>
    

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

    import React, { useState } from "react";
     
    const Toggler = ({ children }) => {
      const [isVisible, setVisible] = useState(true);
      const renderChildren = React.Children.map(children, (el, index) => {
        if (index) return isVisible ? el : null;
        return React.cloneElement(el, { onClick: () => setVisible(!isVisible) });
      });
     
      return renderChildren;
    };
    

    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.

    Read More:  Optimizing Graphql Data Queries with Data Loader

    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:

    <Toggler>
        <div>...here comes some markup that is not related to the toggler...</div>
        <div>
            <Toggler.Trigger>
                <button>toggle</button>
            </Toggler.Trigger>
        </div>
        <div>...here comes some markup that is not related to the toggler...</div>
        <div> 
            <Toggler.Content>
                <div>Content</div>
            </Toggler.Content>
        </div>
    </Toggler>
    

    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:

    const Context = React.createContext();
     
    const addPropsToChildren = (children, props) => 
      React.Children.map(children, el =>
        React.cloneElement(el, props)
      )
     
    class Toggler extends React.Component {
      state = { isVisible: true };
     
      setVisible = () =>
        this.setState(({ isVisible }) => ({ isVisible: !isVisible }));
     
      static Trigger = ({ children }) => (
        <Context.Consumer>
          {({ setVisible }) =>
            addPropsToChildren(children, {
              onClick: setVisible
            })
          }
        </Context.Consumer>
      );
     
      static Content = ({ children }) => (
        <Context.Consumer>
          {({ isVisible }) => isVisible ? children : null}
        </Context.Consumer>
      );
     
      render() {
        return (
          <Context.Provider
            value={{
              isVisible: this.state.isVisible,
              setVisible: this.setVisible
            }}
          >
            {this.props.children}
          </Context.Provider>
        );
      }
    }
    

    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.
    Read More:  19. Node.js Lessons. Safe Way to a FS File and Path

    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:

    <Toggler>
        <Toggler.Trigger>
            <button>toggle</button>
        </Toggler.Trigger>
        <Toggler.Content>
            <div onClick={e => console.log(e)}>Content</div>
        </Toggler.Content>
    </Toggler>
    

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

     static Content = ({ children }) => (
        <Context.Consumer>
          {({ isVisible, setVisible }) =>
              React.Children.map(children, el =>
                  React.cloneElement(el, {
                      onClick={e => {
                          el.props.onClick(e);
                          setVisible();
                      }
                  })
              )
          }
        </Context.Consumer>
      );
    

    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.

     <Toggler>
        <Toggler.Trigger><Button>show modal</Button></Toggler.Trigger>
     
        <Toggler.Content>
          <Modal onOk={() => console.log('Do anything')}>
            <p>Some contents...</p>
          </Modal>
        </Toggler.Content>
      </Toggler>
    

    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:

        (context, el) => ({
            visible: context.isVisible,
            onCancel: context.setVisible,
            onOk: () => {
              context.setVisible();
              el.props.onOk();
            }
          }
    

    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

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Alexander Solovyev

      Related Posts

      Mastering REST APIs: Essential Techniques for Programmers

      December 18, 2024

      Streamlining Resource Allocation for Enhanced Project Success

      December 18, 2024

      Crafting Interactive User Interfaces Using JavaScript Techniques

      December 17, 2024
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      Tips December 31, 2015

      Work With the Customer

      Check what you write. Mind the tenses and forms. Check in translate.google.com or ask colleagues for help. The style and spelling of your writing form the impression of you and your team as a whole. You can agree that the phrase “I work Java scrpt, me have large experience work” sounds ridiculous. Our customer reads the same when you forget about tenses and forms of verbs.

      Development With LAMP Stack Illustrated Address Book Project

      July 22, 2020

      Mastering Common Interview Questions: Strategic Responses Guide

      November 29, 2024

      Visualizing Logs from a Dockerized Node Application Using the Elastic Stack

      January 30, 2020

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC

      Node.js September 30, 2020

      Enhancing Recruitment: The Value of Background and Reference Checks

      Recruitment December 16, 2024

      10 Sorting Algorithms Interview Questions: Theory and Practice for 2019

      Interview June 7, 2019

      Navigating Business Failures: Strategies for Growth and Learning

      Entrepreneurship December 16, 2024

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Angular

      How I Got Started with Angular and TypeScript

      JavaScript

      Node.js Lesson 8: Inheritance from Errors, Error

      Entrepreneurship

      Essential Steps to Identify and Validate Your Business Ideas

      Most Popular

      The Ultimate Guide to Using GitHub Pages

      Beginners

      REST API Design Best Practices

      Programming

      Analyzing Emerging Trends in Health and Medical Marketing

      Medical Marketing
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.