Friday, December 27, 2024
Google search engine
HomeLanguagesWhat are inline conditional expressions in ReactJS ?

What are inline conditional expressions in ReactJS ?

In the react, conditional rendering is the process to show components based on a particular condition. 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.”

In this tutorial, we will go through the concept of inline conditional rendering in React. As the inline condition suggests, we can write the condition in a single line. There are several methods for inline conditional rendering in React. 

Users need to first set up the react project environment on their local computer.

Creating new react project

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

npx create-react-app testapp

Step 2: Now, move inside the project directory using the below command.

cd testapp

Project Directory: It should look like the below image.

Method 1: Inline if-else conditional (ternary) operator
Programmers can use the ternary operator ( ? : ) as a short if-else statement. The ternary operator is a simple javascript operator which takes 3 operands. 

Syntax:

While working with the ternary operator, developers need to wrap the whole expression in curly braces. To improve the readability of the code, users can wrap the operands inside the parenthesis. 

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

When the condition is true, it returns “condition is true” otherwise it returns “condition is false“.  Here, developers can include components as an operand instead of an HTML element. 

Example:

Now, edit the App.js file and add the below code to it.

Filename: App.js

In this file, 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




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" }}>GeeksForGeeks</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;


Command to run: 

npm start

Output: 

In the above output image, the user can see that it shows “user has 3 pending tasks” as the user has a total of 3 tasks to do. 

Method 2: Inline If with Logical && Operator

Here, Logical && operator is a boolean operator which works the same in React as it works in Javascript. It takes 2 conditions as operands. If the first condition is True, it only evaluates the second condition. Here, instead of adding condition as a second operand, we can add react component. So, if the first condition becomes true, it only renders react component. 

Syntax:

Developers need to embed expression with the curly braces. If they need, they can wrap operands inside the parenthesis to keep the code clean. 

{
   (condition) && (React component or HTML code)
}

When the condition evaluates True, It returns the right part (react component or HTML code) as an output…

Example:

Filename: App.js

In this file, we will write a code to render the message according to the value of the ‘totalTask’ variable. 

Javascript




import React, { Component } from 'react';
 
// using inline if with logical && operator
class App extends Component {
    render() {
        const todoList = [];
        const totalTask = todoList.length;
        return (
            <div>
                <h1 style={{ color: "green" }}>GeeksForGeeks</h1>
                {
                    (totalTask > 0) &&
                    (<h2>The user has total {totalTask} task pending</h2>)
                }
                {
                    (totalTask === 0) &&
                    (<h2>The user has not any pending task.</h2>)
                }
            </div>
        );
    }
}
 
export default App;
export default App;


Command to run: 

npm start

Output: 

In the above image, the user can see that it show the message ‘User has no pending task’ as it evaluates (totalTask === 0) condition True.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments