Issue
I have a component that recieve a child and pass it to MUI Menu
export default function MyMenu({children}){
return(
<Menu>
{children ? children : <MenuItem disabled></MenuItem>}
</Menu>
);
}
children has a type children: ReactNode;
and I pass to it menu items like so
<MyMenu>
{condition && (<MenuItem></MenuItem>)}
{condition2 && (<MenuItem></MenuItem>)}
</MyMenu>
I want that when all conditions are false to render a disabled menu item
The problem is that child is never null if I pass children as above. And because of that disabled menu item is never rendered
If all conditions are false then child is an array of false. But in the code I can't treat child prop as an array to check whether it contains only false values
Solution
How about using React.Children.toArray:
const MyMenu = ({ children }) => {
const hasChildren = React.Children.toArray(children)
.filter(Boolean)
.length > 0
if (hasChildren) {
return children
}
return <MenuItem disabled />
}
Note: Not tested.
Answered By - Marces Engel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.