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

143
Vistas
React conditional style with more than 2 cases - smarter way than using a self-invoking function?

When I have more than 2 options for conditional style in React, I'd rather not have ternary conditions within ternary conditions, so I use a self-invoking function like this:

const HeaderLink = ({
  label,
  linkTo,
  firstItem = false,
  lastItem = false,
}: {
  label: string;
  linkTo: string;
  firstItem?: boolean;
  lastItem?: boolean;
}) => {
  return (
    <div
      id="HeaderLink"
      style={{
        padding: (() => {
          if (firstItem) return "0 1vw 0 0";
          if (lastItem) return "0 0 0 1vw";
          return "0 1vw";
        })(),
      }}
    >
      <Link href={linkTo}>{label}</Link>
    </div>
  );
};

It works, but is there a smarter way? Are there reasons to avoid this pattern?

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You may want to reuse your function

But even if you won't, even in that case you might want to have an easy time reading your code and define the function only once. Instead of a self-invoking function, you may create a function, like

function getWV(firstValue, secondValue) {
    alert("I have been executed");
    //...do your stuff
}

//proof-of-concept
getWV('a', 'b');

The example above shows that you can achieve a one-liner in your rendering code, only calling the function instead of defining it each time you render it and obscuring the readability of the renderer.

You can use helpful arrays

let array = ["0 1vw 0 0", "0 0 0 1vw", "0 1vw"];

function getItem(items)
{
    let filteredArray = items.filter((item) => !!item);
    if (filteredArray.length) return array[items.indexOf(filteredArray[0])];
    return array[items.length];
}

console.log(getItem([null, 3]));
console.log(getItem([null, 0]));

At first sight this code may not appear much better than yours, but imagine the case when you may have more than two values. In that case you would have as many if conditionals as many items, while the approach above is much more dynamic.

almost 4 years ago · Santiago Trujillo 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