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

109
Visualizações
Self-closing element conditional element using only one line?

I would like to render a component out of two depending on a flag value. I was wondering if there is a way to do this in only one line?

I was thinking something like this: <(flag ? Comp1 : Comp2) att1={attValue} ... />

If there is not a way, is it possible to somehow add it as a feature in the future?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can interpolate a React.createElement that alternates between the two components.

<>
  {
    React.createElement(flag? Comp1 : Comp2, { att1: attValue }, null)
  }
</>
about 4 years ago · Juan Pablo Isaza Relatório

0

I know 2 ways of doing this the JSX way. Even though they all require more than one line, I think they are still DRY and help you avoid errors from code duplication. This goes without saying, but your components must receive the same props for these approaches to work.

The first one is to create a variable for your desired component, then render it (note that this variable name must start with an uppercase letter).

const YourComp = flag ? Comp1 : Comp2;

<YourComp att1={attValue} ... />

The second way is to create a variable for your props, then spread it:

const props = {
  attr1: attrValue,
  ...
}

{flag ? <Comp1 {...props} /> : <Comp2 {...props} />}
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