dimanche 29 août 2021

Which is the best approach to handle nested conditional rendering?

I recently installed eslint-config-airbnb and decided to review a project by using their style guide. Since it is not advised to nest ternary operators I found myself converting the following block:

<div>
  { index === 0 ? <StatusButton big programmed statusText="Programmed" />
  : index === 1 ? <StatusButton big confirmed statusText="Confirmed" />
  : <StatusButton big soldOut statusText="Sold Out" />; }
</div>

Into:

<div>
    {(() => {
      if (index === 0) {
        return (
          <StatusButton
            big
            programmed
            statusText="Programmato"
          />
        );
      }
      if (index === 1) {
        return (
          <StatusButton big confirmed statusText="Confermato" />
        );
      }
      return <StatusButton big soldOut statusText="Sold Out" />;
    })()}
</div>

The reason of the rule no-nested-ternary is that the code should be more easier to read by using if, but honestly, I think that's not true. Since I have relatively little experience with JS I would like to understand your point of view. Thank you.

Aucun commentaire:

Enregistrer un commentaire