Inline if-else conditional (ternary) operator

The ternary operator ( ? : ) is a short if-else statement. The ternary operator is a simple javascript operator which takes 3 operands. 

Syntax

{condition ? ("condition is true") : ("condition is false") }

When the condition is true, it returns “condition is true” otherwise it returns “condition is false“.  Here, we can replave these string with the JSX components. 

Example Here, we will declare a variable name ‘totalTask’ and assign a value to this. Next, we will use the ternary operator to show the different messages according to the value of the ‘totalTask‘ variable. 

Javascript




// App.js
import React, { Component } from "react";
 
// Rendering different message according
// to the value of total task variable
class App extends Component {
    render() {
        const todoList = [
            "write article",
            "read article",
            "Review article",
        ];
        const totalTask = todoList.length;
        return (
            <div>
                <h1 style={{ color: "green" }}>
                    w3wiki
                </h1>
                <b>
                    {totalTask > 0 ? (
                        <h2>
                            The user has total
                            {totalTask} task pending
                        </h2>
                    ) : (
                        <h2>
                            The user has not any
                            task pending
                        </h2>
                    )}
                </b>
            </div>
        );
    }
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

What are inline conditional expressions in ReactJS ?

In React conditional rendering is the process of showing components based on a particular condition. With inline conditional expression in React, we can write the condition in a single line. For example, While building the to-do list app, developers should show a task only if any pending task is available otherwise they can show a message like “There is no pending task available.”

We can use inline Conditions in React with the following approaches

Table of Content

  • Inline if-else conditional (ternary) operator
  • Inline If with Logical && Operator

Similar Reads

Steps to create React Application

Step 1: To create a new react app, run the below command on your terminal....

Project Structure:

...

Method 1: Inline if-else conditional (ternary) operator

The ternary operator ( ? : ) is a short if-else statement. The ternary operator is a simple javascript operator which takes 3 operands....

Method 2: Inline If with Logical && Operator

...

Contact Us