Logical AND Operator in ReactJS
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:
1 | {PART_A && PART_B} |
If PART_A become true then PART_B will execute. It’s the same as the code below.
1 2 3 | 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.
1 2 3 4 5 | // 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
1 2 3 4 5 6 7 8 9 10 | 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:
Thank you for reading. Happy Coding!