Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!