3

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.

5
  • Nested ternaries? Or just write a damn if - else if - else :) Commented Nov 2, 2021 at 10:36
  • Why not have if return? No need for else Commented Nov 2, 2021 at 10:51
  • @evolutionxbox Then you might need to duplicate the wrapper code in every return. Commented Nov 2, 2021 at 10:53
  • @YuryTarabanko oooo, what about a render function? Commented Nov 2, 2021 at 10:54
  • Yeah, might also work. <Container>{(() => {})()}</Container> Commented Nov 2, 2021 at 10:56

2 Answers 2

3

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} />,
  ];
}
Sign up to request clarification or add additional context in comments.

1 Comment

@cts Glad I could help. Ternary is just an expression so you can have it anywhere you can put expression. Just be careful to not make it unreadable.
1

You can use this template :

return (
    <Container>
      {booleanValueOne && (
        <TrueComponent props={props} />
      )}
      {(!booleanValueOne && booleanValueTwo) && (
        <TrueComponentTwo props={props} />
      )}
      {(!booleanValueOne && !booleanValueTwo) && (
        [
          <DefaultComponentOne props={props} />,
          <DefaultComponentTwo props={props} />,
        ]
      )}
    </Container>
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.