Reputation: 199
I'm working on menu component storybook where i have mapped icon & text , problem is i have horizontal divider in between , how do i Map it with icons & text.From below code i'm getting divider at the bottom of the Menu. I'm trying to achieve as it is in the image. In the storybook i have to map few menu variants as in mui, for that i cannot hardcode divider, if there is any way i can manage it with Map or any other method. Thanks.
export const Menu= ({ icons }) => {
return (
<Paper sx={{ width: 320, maxWidth: '100%' }} >
<MenuList>
{icons.map((item) => (
<MenuItem>
<ListItemIcon fontSize="small">{item.icon}</ListItemIcon>
<ListItemText>{item.label}</ListItemText>
<Typography variant="body2" color="text.secondary">{item.typography}</Typography>
</MenuItem>
))}
<Divider /> /* how do i map this */
</MenuList>
</Paper >
);
}
Stories.js
icons: [
{ icon: <ContentCut fontSize="small" />, typography: "⌘X", label: "Cut" },
{ icon: <ContentCopy fontSize="small" />, typography: "⌘C", label: "Copy" },
]
Upvotes: 1
Views: 1631
Reputation: 175
Answer:
If you want the divider to be just one then don't map over it . thats the purpose of the .map()
method.
and To Acheive the required results i just removed <Menu></Menu>
Component and Just Kept the <Papper></Papper>
Component
Notes :
In terms of how to Map the Divider with the below example ,you can just wrap it in a empty react fragment<></>
and map over the <MenuItem></MenuItem>
.
Only issue is that youll get an error in your key
props which will say its not unique it can be fixed by assigning index
key like the example below and wrap the <MenuItem></MenuItem>
Component in It. However thats not best practice ,
<React.Fragment></React.Fragment>
Is better practice according to Keyed Fragment React 18 Docs to add a key
prop However that's giving a New Error in MUI.
Thats not an issue since were mapping over the MenuItem
Component , However if we use for example in @Nathan Comments <React.Fragment key={index}></React.Fragment>
or my previous answer to use <></>
we would be mapping over the React.Fragment
Itself or the empty fragment and would get a new error MUI: The Menu component doesn't accept a Fragment as a child.
Uncomment the Examples in the Sandbox Check the sandbox console.
Check Code Code SandBox
Solution
export const MenuIcon = ({ menuicons }) => {
return (
<Paper sx={{ width: 320, maxWidth: "100%" }}>
{menuicons.map((item, index) => (
<MenuItem key={item + index}>
<ListItemIcon fontSize="small">{item.icon}</ListItemIcon>
<ListItemText>{item.label}</ListItemText>
<Typography variant="body2" color="text.secondary">
{item.typography}
</Typography>
</MenuItem>
))}
<Divider />
<ListItemIcon fontSize="small">
ClipBoard <ContentCopyIcon fontSize="small" />
</ListItemIcon>
</Paper>
);
}
References
Empty Fragment Syntax React Docs
Stack OverFlow Question MUI Icons - as props
.map() method Syntax - MDN Docs
Upvotes: 2