I have this component that can take a single child or multipipe children, here it is with multiple
<SideDataGridItem>
<div id='top'>
<div>A1</div>
<div>B1</div>
<div>C1</div>
</div>
<div id='bottom'>
<div>A2-</div>
<div>B2-</div>
<div>C2-</div>
</div>
</SideDataGridItem>
and here it is with a single child
<SideDataGridItem>
<div id='top'>
<div>A1</div>
<div>B1</div>
<div>C1</div>
</div>
</SideDataGridItem>
I want to be able to map over the children of the child.
Here's my attempt that doesn't work...
import { ReactElement, Children } from 'react';
export interface PropsShape {
children: ReactElement | ReactElement[];
}
const SideDataGridItem = ({ children }: PropsShape): ReactElement => {
const childArr = Children.toArray(children);
return (
<>
{childArr[0] &&
childArr[0].map(function (item: any, i: number) {
return (
<div key={i}>
{item}- {i}
</div>
);
})}
{childArr[1] &&
childArr[1].map(function (item: any, i: number) {
return (
<div key={i}>
{item}- {i}
</div>
);
})}
</>
);
};
export { SideDataGridItem };
the error I get is a red squiggle on the .map...
Property 'map' does not exist on type 'ReactChild | ReactFragment | ReactPortal'.
Property 'map' does not exist on type 'string'.
because it's trying to loop over a single item when really I want to loop over its children!
the correct answer will not output a div with an id of 'top' or 'bottom' it will simply map over the children of that div with the id
Attempt 2
import { ReactElement, Children } from 'react';
export interface PropsShape {
children: ReactElement | ReactElement[];
}
const SideDataGridItem = ({ children }: PropsShape): ReactElement => {
const childArr = Children.toArray(children);
return (
<>
// map over the childArr
{childArr.map(function (item: any) {
// for each item inside the childArr map over them ?? expecting just 3 items not 4 or 1
{
item.map(function (itemInner: any, i: number) {
return (
<div key={i}>
{itemInner}- {i}
</div>
);
});
}
})}
</>
);
};
export { SideDataGridItem };
Attempt 3
If I log out childArr
I get
Here we can see the array of the 3 items I want to map over in
childArr[0].props.children
when I try and map over it I get
{childArr[0] &&
childArr[0].props.children.map(function (item: any, i: number) {
return (
<div key={i}>
{item}- {i}
</div>
);
})}
with the error
Property 'props' does not exist on type 'ReactChild | ReactFragment | ReactPortal'.
Property 'props' does not exist on type 'string'.