REACT: children.map is not a function

REACT: children.map is not a function

I come across this error today in my Next.js app.
When I found the solution I realized that I had already stumbled upon it not so long ago ... but I had forgotten.
That's the reason why I'm writing this little post :-)

This piece of code

...
export default function ImagesContainer({ children }) {
  let childImages = children.map((childImg) => {
    return <div className={styles["image-item"]}>{childImg}</div>;
  });

  return <div className={styles["images-container"]}>{childImages}</div>;
}

had already proven to work but, suddenly, it raised

Selection_003.jpg The reason was the component had only ONE child and therefore the "children prop" value is not treated as an array ("children prop" is a shapeshifter in React), so I can't invoke "map()" on it.

I had forgotten that, to work with components' children, it's better to use React.Children
Among the functions provided by this utility (built-in in React) there is indeed the map() function for the job ( React.Children doc)

React.Children.map(children, function[(thisArg)])

So my code become like this and it works.

import React from "react";
....

export default function ImagesContainer({ children }) {
  let childImages = React.Children.map(children, (childImg) => {
    return <div className={styles["image-item"]}>{childImg}</div>;
  });

  return <div className={styles["images-container"]}>{childImages}</div>;
}


Did I write anything wrong ? Or you have better ideas?
Please share it in the comments :-)

Photo by Francisco De Legarreta C. on Unsplash