Home / Snippets / How to Write Conditional Statements in JSX
How to Write Conditional Statements in JSX cover

How to Write Conditional Statements in JSX

219

2 years ago

0 comments

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>
}
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this