I am working on next.js project, where we are calling API and showing data on Dashboard,
While Loading data we are showing Skeleton for cards or any other UI Components for same/look-a-like view.
const skeletonDom = () => {
return (
<>
<Grid container spacing={4} xs={12}>
<Grid item xs={12}>
<Skeleton variant='rounded' height={320} />
</Grid>
<Grid item xs={12} md={4}>
<Skeleton variant='rounded' height={200} />
</Grid>
<Grid item xs={12} md={4}>
<Skeleton variant='rounded' height={200} />
</Grid>
<Grid item xs={12} md={4}>
<Skeleton variant='rounded' height={200} />
</Grid>
</Grid>
</>
)
}
if loading is true, I am showing this layout.
What I want to achieve is I want to make function which takes object as props, return me above code.
like if I input:
const skeletonObj = [
{
type: 'parent',
tag: 'Grid',
props: {
container: true,
spacing: 4,
xs: 12
},
children: [
{
type: 'child',
tag: 'Grid',
props: {
item: true,
xs: 12
},
children: [
{
type: 'child',
tag: 'Skeleton',
props: {
variant: 'rounded',
height: 320
}
}
]
}
]
}
]
I have tried map as well as loop but I am not able to get desire output.
Can someone write/help me to write function
like : generateSkeleton(skeletonObj)
, that return me
<Grid container spacing={4} xs={12}>
<Grid item xs={12}>
<Skeleton variant='rounded' height={320} />
</Grid>
<Grid item xs={12} md={4}>
<Skeleton variant='rounded' height={200} />
</Grid>
<Grid item xs={12} md={4}>
<Skeleton variant='rounded' height={200} />
</Grid>
<Grid item xs={12} md={4}>
<Skeleton variant='rounded' height={200} />
</Grid>
</Grid>
CodePudding user response:
Below code will generate the UI as you expected.
One suggestion I'd give that instead of assign string value to tag
property, assign it to the component you wants to render like Grid
. Otherwise, you have to use if/else
or switch
for rendering the right component.
// import your Grid and Skeleton components
import {Grid , Skeleton} from "@mui/material";
const skeletonObj = [
{
type: "parent",
tag: Grid,
props: {
container: true,
spacing: 4,
xs: 12
},
children: [
{
type: "child",
tag: Grid,
props: {
item: true,
xs: 12
},
children: [
{
type: "child",
tag: Skeleton,
props: {
variant: "rounded",
height: 320
}
}
]
},
{
type: "child",
tag: Grid,
props: {
item: true,
xs: 12
},
children: [
{
type: "child",
tag: Skeleton,
props: {
variant: "rounded",
height: 320
}
}
]
}
]
}
];
function generateSkeleton(skeleton) {
if (!skeleton || skeleton.length <= 0) return "";
return skeleton.map((c, idx) => {
return <c.tag key={idx} {...c.props}>{generateSkeleton(c.children)}</c.tag>;
});
}