Clue Mediator

Logical AND Operator in ReactJS

📅January 8, 2020

Today we will show you how to use logical AND operator in ReactJS with example. It's also known as short circuit evaluation.

Logical AND Operator in ReactJS, Conditional Rendering – React JS, && Operator in ReactJS, react: render conditionally from props, react || operator, react render component onclick, react conditional rendering best practices.

Checkout more articles on ReactJS

Use curly braces to embed AND Operator (&&) in JSX. Let’s consider two parts for syntax understanding.

Syntax:

{PART_A && PART_B}

If PART_A become true then PART_B will execute. It’s the same as the code below.

if(PART_A) {
  PART_B
}

Example:

Refer previous article: Ternary Operator in ReactJS

Let's refer to the same example of the previous article where we will convert the `Tab.js` code into the logical && operator.

// Logical AND Operator
return showTab && <div style={{ marginTop: 10 }}>
  ...
  ...
  </div>

After changing the code of Tab component, your `Tab.js` file should be same as below.

Tab.js

import React from 'react';

const tab = (showTab) => {
// Logical AND Operator
return showTab && <div style={{ marginTop: 10 }}>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
}

export default tab;

Here we have changed the code in only single file (`Tab.js`), everything else will remain the same.

Output:

Output - Logical AND Operator in ReactJS - Clue Mediator

Output - Logical AND Operator in ReactJS - Clue Mediator

Thank you for reading. Happy Coding!

Demo & Source Code

Github Repository StackBlitz Project