Yogesh Chauhan's Blog

Use inline if to make a shorter conditional syntax in React

in React on May 5, 2021

To use the the components in React conditionally we can make use of if-else conditions in JavaScript.

In this React rendering example we saw how we can do that. But what if we want a shorter syntax? We can use inline conditions in JSX to do that.

There are two different ways we can use inline if in React.

Inline If with Logical && Operator

Just embed the expressions by wrapping them into curly braces including the JavaScript logical operator (&&).

Just like this:



{unreadMessages.length > 0 &&
  <h2>
    You have {unreadMessages.length} unread messages.
  </h2>
}



This is how it works:

  • true && expression => expression
  • false && expression => false

So, if the condition before && is true then React will go for the code after && and will render the output. If not, React will ignore it and skip the execution of the code after &&.

Here’s the demo:


Inline If-Else with Conditional Operator

You can also use Conditional Operator in JavaScript for inline conditional rendering.

Like this:


condition ? true : false

Just like this example we can just conditionally render one or more words.

It doesn’t have to be just one word. We can use it with a larger expressions as well.


Let’s try to change the elements storing in variables example


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
4 ways to create Date Objects in JavaScriptJavaScriptObservation of Human Behavior [Shopping Observation Example]MiscellaneousWhat is ECMAScript?JavaScriptOpen Source Security Tools for Defense SecurityMiscellaneousHow to Secure Web or Mobile Browsers?MiscellaneousHow to use PHPMailer to send an Email via Gmail SMTP Server?PHP