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

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

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 Denunciar

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 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