YogeshChauhan . com

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 &&
    You have {unreadMessages.length} unread messages.

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Full and Partial CUBE in Postgres with ExamplesPostgresMIN, MAX, COUNT, AVG and SUM in SQLSQL/MySQLWhat are partials in SCSS (Sass)?SCSSHow to get Current Hour, Minute and Second in JavaScript?JavaScriptSQL GROUP BY StatementSQL/MySQLWhat is a “promise” in JavaScript?JavaScript