Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda