Posts Learn Components Snippets Categories Tags Tools About
/

How to Write Conditional Statements in JSX

Learn how to write or define conditional statements in JSX using short circuit evaluation and early returns

Created on Mar 22, 2022

207 views

To write conditional statements in JSX you can make use of short-circuit evaluation for simpler conditions and for complex conditions, you can make use of early returns.

Short Circuit Evaluation


So instead of writing your JSX like below:
function SampleComponent({ isTrue }) {
  return isTrue ? <p>True!</p> : null;
};
You can make use of short circuit evaluation like the following:
function SampleComponent({ isTrue }) {
  return isTrue && <p>True!</p>;
};
The important part for it is the && (AND) operator which will determine how the value should be returned.

Simple Early Returns


If you are dealing with complex conditions, it's recommended to use simple early returns where each condition automatically returns the necessary value.
function SampleComponent({ a, b, c, d, e }) {
  const condition = a && b && !c;

  if (!condition) return <p>Foo</p>;

  if (d) return <p>Bar</p>;

  if (e) return <p>Baz</p>;

  return <p>Qux</p>
}

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Write Conditional Statements in JSX

)