Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
What condition should be applyed to child component in order to render conditionally

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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>
    );
}
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!