Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda