Conditional rendering of React components without using ternary operators

Hi currently have the following code React code:

  return (
    <Container>
      {booleanValueOne ? (
        <TrueComponent props={props} />
      ) : (
        [
          <DefaultComponentOne props={props} />,
          <DefaultComponentTwo props={props} />,
        ]
      )}
    </Container>
  );

So if booleanValueOne is true we return <TrueComponent and if not returning an array of DefaultComponents. This is straightforward.

But I since want to add a second boolean value: booleanValueTwo – and if it’s true, return TrueComponentTwo & if neither of booleanValueOne or booleanValueTwo are true, returning the array of default components.

Can anyone share best practises for doing so?

I can’t use a ternary as I have 3 possible outcomes.

Answer

You can have nested ternaries. Should be readable if properly aligned

const result = booleanValueOne ? (
  <TrueComponent props={props} />
) : booleanValueTwo ? (
  <TrueComponentTwo props={props} />
) : (
  [<DefaultComponentOne props={props} />, <DefaultComponentTwo props={props} />]
);


return (<Container>{result}</Container>)

Or you could use normal control flow if - else if to assign correct value to result variable.

let result = null;

if (booleanValueOne) {
  result = <TrueComponent props={props} />;
} else if (booleanValueTwo) {
  result = <TrueComponentTwo props={props} />;
} else {
  result = [
    <DefaultComponentOne props={props} />,
    <DefaultComponentTwo props={props} />,
  ];
}