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

How to Write Conditional Statements in JSX

204

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

Ahmad Aziz

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 ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this