-1

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • This is a question of opinions At airbnb - folks find it hard read apparently. If you don't - disable the rule maybe? – madflow Aug 29 '21 at 13:28

3 Answers3

1

You can render in multiple ways ,

Option - 1

const getStatusButton = (index) => {
  switch (index) {
    case 0: {
      return <StatusButton big programmed statusText="Programmato" />;
    }
    case 1: {
      return <StatusButton big confirmed statusText="Confermato" />;
    }
    default: {
      return <StatusButton big soldOut statusText="Sold Out" />;
    }
  }
};

So when rendering you can call this function

{
  getStatusButton(index);
}

Option - 2

Have an function which gives you the different props

const getStatusButtonProps = (index) => {
  switch (index) {
    case 0: {
      return {
        programmed: true,
        statusText: "Programmato",
      };
    }
    case 1: {
      return {
        confirmed: true,
        statusText: "Confermato",
      };
    }
    default: {
      return {
        soldOut: true,
        statusText: "Sold Out",
      };
    }
  }
};

Now you can just use one Status Button

<StatusButton big {...getStatusButtonProps(index)} />
Shyam
  • 5,292
  • 1
  • 10
  • 20
0

Just use switch case statement. I.e.

switch (index) {
case 0:
  return <StatusButton...

case 1:
  return <StatusButton...

default:
  return <StatusButton...
}
Maksim.T
  • 531
  • 4
  • 17
0

How about this

<div>
    <StatusButton
        big 
        programmed={index === 0}
        confirmed={index === 1}
        soldOut={index !== 0 || index !== 1}
        statusText={getStatusText(index)} />
</div>


getStatusText = (index) => {
    switch(index) {
        case 0: return "Programmed";
        case 1: return "Confirmed";
        default: return "Sold Out"
    }
}
sojin
  • 2,158
  • 1
  • 10
  • 18