Skip to content

Commit 11675c7

Browse files
committed
✨ Logical and Operator
1 parent 175151a commit 11675c7

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

docs/logical-and-operator.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
id: logical-and-operator
3+
sidebar_label: Logical && operator
4+
title: Logical && Operator
5+
description: Logical && operator | React Patterns, techniques, tips and tricks in development for Ract developer.
6+
keywords: ['logical && operator', 'react logical && operator', 'reactpatterns', 'react patterns', 'reactjspatterns', 'reactjs patterns', 'react', 'reactjs', 'react techniques', 'react tips and tricks']
7+
version: Logical && operator
8+
image: /img/reactpatterns-cover.png
9+
---
10+
11+
It happens often that you want to render either an element or nothing. You could have a `LoadingIndicator` component that returns a loading text or nothing. You can do it in JSX with an if statement or ternary operation.
12+
13+
```jsx
14+
function LoadingIndicator({ isLoading }) {
15+
if (isLoading) {
16+
return (
17+
<div>
18+
<p>Loading...</p>
19+
</div>
20+
)
21+
} else {
22+
return null
23+
}
24+
}
25+
26+
function LoadingIndicator({ isLoading }) {
27+
return (
28+
<div>
29+
{ isLoading
30+
? <p>Loading...</p>
31+
: null
32+
}
33+
</div>
34+
)
35+
}
36+
```
37+
38+
But there is an alternative way that omits the necessity to return null. The logical `&&` operator helps you to make conditions that would return null more concise.
39+
40+
How does it work? In JavaScript a `true && 'Hello World'` always evaluates to `Hello World` and a `false && 'Hello World'` always evaluates to false.
41+
42+
```jsx
43+
const result = true && 'Hello World'
44+
console.log(result)
45+
// Hello World
46+
47+
const result = false && 'Hello World'
48+
console.log(result)
49+
// false
50+
```
51+
52+
In React you can make use of that behaviour. If the condition is true, the expression after the logical `&&` operator will be the output. If the condition is false, React ignores and skips the expression.
53+
54+
```jsx
55+
function LoadingIndicator({ isLoading }) {
56+
return (
57+
<div>
58+
{ isLoading && <p>Loading...</p> }
59+
</div>
60+
)
61+
}
62+
```
63+
64+
That's your way to go when you want to return an element or nothing. It makes it even more concise than a ternary operation when you would return null for a condition.

sidebars.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ module.exports = {
1717
'Conditional rendering': [
1818
'if-else',
1919
'ternary-operation',
20+
'logical-and-operator',
2021
],
2122
},
2223
],

0 commit comments

Comments
 (0)