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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Why it’s not a good idea to create Number objects in JavaScript?JavaScriptDISTINCT ON: The confusing, unique and useful feature in PostgresPostgresStyling Lists with CSSCSSKeyValuePipe in Angular 9AngularThe * arithmetic operator in Envision BasicEnvision BasicUnderstand Inheritance in PHP in this Basic Example (For Beginners)PHP