Bhavik Chavda
bhavikchavda

bhavikchavda

React Children and Its use cases

React Children and Its use cases

Overview of react components, how to use children prop in component, and various use-cases of children prop

Bhavik Chavda's photo
Bhavik Chavda
·Apr 4, 2022·

4 min read

Table of contents

  • Overview of React Components
  • children props

React is an open-source javascript library for building user interfaces. so let's understand about components a bit and then learn how to use the children prop for various purposes.

Overview of React Components

  • React apps are made up of core building blocks called components. Components allow us to split applications into smaller, reusable parts. There are two ways of creating components: function and class-based components.
  • We can props to pass data from one component to another. Props are just a shorter way of saying properties.

  • Here is an example of a Card component that takes heading and description as props,

import React from "react";

const Card = ({ heading, description }) => {
  return (
    <div className="card">
      <div className="header">
        <h3>{heading}</h3>
      </div>
      <div className="description">{description}</div>
    </div>
  );
};

// Using Card component
export default function App() {
  return <Card 
    heading="My Status" 
    description="Lorem ipsum dolor sit amet" 
  />
}

children props

  • children prop in a component is used to display whatever we include between the opening and closing tags when using a component.

  • children is used as props.children in the functional component, and this.props.children in the Class component.

  • Here are various ways to use the children prop,

1. Using children as a placeholder

  • We can use the children prop as a placeholder, to show any content added between the opening and closing tag while using the component.
  • Let's understand it with the Card component example,
import React from "react";

const Card = ({ heading, children }) => {
  return (
    <div className="card">
      <div className="header">
        <h3>{heading}</h3>
      </div>
      <div className="description">{children}</div>
    </div>
  );
};

// Using Card component
export default function App() {
  return (
    <div>
      <Card heading="My Status">
        <ul>
          <li>Lorem ipsum dolor sit</li>
          <li>Consectetur adipiscing elit</li>
          <li>Nulla nulla lacus</li>
        </ul>
      </Card>
    </div>
  );
}

2. Using children as a function

  • We can use children as a function too.
  • For example, let's build a Generic Component that takes an API URL, and based on API status we show content. It is going to be used in many places and the content to be shown varies in each usage.
import React, { useEffect, useState } from "react";

const DataFetcher = ({ url, children }) => {
  const [data, setData] = useState({
    loading: false,
    data: null,
    errorMessage: null
  });

  useEffect(() => {
    (async () => {
      try {
        setData({
          loading: true,
          data: null,
          errorMessage: null
        });
        let response = await fetch(url);
        response = await response.json();
        setData((oldData) => ({
          ...oldData,
          loading: false,
          data: response
        }));
      } catch (error) {
        setData((oldData) => ({
          ...oldData,
          loading: false,
          errorMessage: error.message
        }));
      }
    })();
  }, [url]);

  return typeof children === "function" ? children({ ...data }) : null;
};

// Using DataFetcher component
export default function App() {
  return (
    <div>
      <DataFetcher url="https://jsonplaceholder.typicode.com/todos/1">
        {({ loading, data, errorMessage }) => {
          if (loading) return "loading...";
          if (errorMessage) return `Error:- ${errorMessage}`;
          if (data) return JSON.stringify(data);
          return "";
        }}
      </DataFetcher>
    </div>
  );
}

3. Alter the children

  • React.Children provides utility to deal with children data structure.
  • React.Children has the following utility functions,
    • map and forEach to iterate over children
    • count to cout children elements
    • only to verify that children have only one child and return it
    • toArray to convert children into an array and assign a key to each element

Let's understand it with an example,

  • You want to build a component that takes a set of div that has title property and converts it into collapsible sections.
  • To build it we have to access the child element properties and return modified elements.
import React from "react";

const Collapses = ({ children }) => {
  return React.Children.map(children, (child) => {
    if (child.type === "div" && child.props.title) {
      return (
        <details>
          <summary>{child.props.title}</summary>
          <div>{child.props.children}</div>
        </details>
      );
    }
    return null;
  });
};

export default function App() {
  return (
    <Collapses>
      <div title="Section 1">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <p>Etiam non dolor risus.</p>
      </div>
      <div title="Section 2">
        <p>Phasellus rhoncus risus sed semper sodales.</p>
      </div>
    </Collapses>
  );
}

These are some of the ways we can use children prop to accomplish our needs. Do you use React.Children in any other ways also? Please comment

 
Share this