react.children 1


import React from 'react';

type Props = {
  children: JSX.Element[] | JSX.Element;
  margin: number;

export default function Stack({ children, margin }: Props) {
  function wrapChildren() {
    return, (child) =>
      React.cloneElement(child, { style: {, marginBottom: `${margin}px` } }),

  return <>{wrapChildren()};

Here is what the above code is Doing:
1. We’re creating a function called `wrapChildren` that takes in the `children` prop and returns a new array of children.
2. We’re using the `` function to iterate over the children and return a new array of children.
3. We’re using the `React.cloneElement` function to clone each child and add a new `style` prop to it.
4. We’re using the spread operator to merge the existing `style` prop with the new `marginBottom` style.
5. We’re returning the new array of children.

Now, let’s use the `Stack` component in our `App` component:

import React from ‘react’;
import Stack from ‘./Stack’;

function App() {
return (



export default App;

Here’s what the above code is doing:
1. We’re importing the `Stack` component.
2. We’re using the `Stack` component and passing in a `margin` prop.
3. We’re passing in two `div` elements as children to the `Stack` component.

Now, let’s run the app and see what happens:

![Stack component](./images/stack-component.png)

As you can see, the `Stack` component is working as expected.

## Conclusion

In this tutorial, we learned how to use the `React.Children` API to clone and map children in React.

## References

– [React.Children](
– [](
– [React.Children.forEach](
– [React.Children.count](
– [React.Children.only](
– [React.cloneElement](
– [React.isValidElement](

Similar Posts