Conditional in JSX

Instead of

const sampleComponent = () => {
  return isTrue ? <p>True!</p> : null
};

Use short-circuit evaluation

const sampleComponent = () => {
  return isTrue && <p>True!</p>
};

For Complex scenarios with too many ternaries:

// Y soo many ternary??? :-/
const sampleComponent = () => {
  return (
    <div>
      {flag && flag2 && !flag3
        ? flag4
        ? <p>Lorem</p>
        : flag5
        ? <p>Ipsum</p>
        : <p>Dolor</p>
        : <p>Sit Amet</p>
      }
    </div>
  )
};
  • Best approach: Move logic to sub-components

  • Alternate hacky approach: Use IIFE

There are some libraries that solve this problem (JSX-Control Statements), but rather than introduce another dependency use an IIFEarrow-up-right and return values by using if-else statement inside

With an appropiate transpilerarrow-up-right you can take advantage of the upcoming do expressionarrow-up-right which is currently on stage-1arrow-up-right

Or alternatively simply use early returns

Last updated