Home > Software engineering >  What condition should be applyed to child component in order to render conditionally
What condition should be applyed to child component in order to render conditionally

Time:02-04

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

CodePudding user response:

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.

CodePudding user response:

Can you use React.Children.count(children) and try :

export default function MyMenu({children}){
    
   return(
        <Menu>
            {React.Children.count(children) ? children : <MenuItem disabled></MenuItem>}
          </Menu>
    );
}

CodePudding user response:

you can filter the children array (if it wasn't an array it will be a primitive value) to remove the nil values from it, here is an example:

const MyMenu = ({ children }) => {
  const tmp = Array.isArray(children)
    ? compact(children)
    : isNil(children)
    ? undefined
    : children;

  return <div>{tmp || tmp.length > 0 ? tmp : "DISABLED"}</div>;
};

sandbox: https://codesandbox.io/s/reactjs-lab-n791v?file=/src/labPages/Experiments/test_files/8/index.jsx

  •  Tags:  
  • Related