The brilliant idea of mapping through children came about when creating compound components.
Made a discovery today and I just thought I'd share. This may or may not be a legendary breakthrough for some of you but it was for me. This post should be pretty short.
The Discovery
I was working on an application today and I needed to create a custom slider component that takes divs with content in them but it should only render divs. I needed to prevent other html/js elements from being displayed inside of this slider so I can control the styling and the slide itself to remain consistent between one another.
Typically, I would just create an object that holds the content and then create a template for each slide and map through them anytime I use the component.
I had this bright idea that children in a React component takes all of the elements within an element and turns it into an array. We all know that if you have an array you can use all of the javascript built in functions to manipulate that array.
Well in almost every React application I use the .map function in some place or form. So I gave it a try in my code!
const CustomComponent = ({ title, children, ...rest }) => {
return (
<>
{children.map((child) => {
<div key={child.id}>{child}</div>;
})}
</>
);
};
👍🏾 Thanks for reading.