How to Map the Children of a Parent Component in React?

Sometimes, we want to map the children of a parent component in React.

In this article, we’ll look at how to map the children of a parent component in React.

Map the Children of a Parent Component in React

To map the children of a parent component in React, we can use the React.Children.map method.

For instance, we write:

import React from "react";

const Wrapper = ({ children }) => (
  <div style={{ color: "red" }}>{children}</div>
);

const OpaqueWrapper = ({ children }) =>
  Array.isArray(children) ? (
    <Wrapper>
      {React.Children.map(children, (child) =>
        React.cloneElement(child, {
          style: { ...child.props.style, opacity: 0.5 }
        })
      )}
    </Wrapper>
  ) : null;

export default function App() {
  return (
    <div>
      <OpaqueWrapper>
        <p style={{ fontWeight: "bold" }}>foo</p>
        <p>bar</p>
        <p>baz</p>
      </OpaqueWrapper>
    </div>
  );
}

We have the Wrapper that takes the children components and wrap them in a div.

And we set the color of the content to red.

Then we have the OpaqueWrapper that takes the children prop and calls the React.Children.map with children and a callback to return the components that we cloned with React.cloneElement.

During the processing of cloning, we set the style prop to merge the style prop in the original child component and combine it with opacity set to 0.5 with the spread operator.

Now we should see foo being red, bold and translucent and the rest of the text are red and translucent.

Conclusion

To map the children of a parent component in React, we can use the React.Children.map method.