Listing 3-10: Conditional Rendering with &&
import Header from './Header';
function Welcome({loggedIn}){
return (
<div>
{loggedIn&&<Header />}
Note: if you don't see the welcome messsage,
you're not logged in.
</div>
)
}
export default Welcome;
Conditional Rendering with &&
The &&
operator relies on the fact that any operand in JavaScript can be converted to a Boolean true
or a Boolean false
. The following values evaluate to false
:
- false (Boolean false)
- 0 (The number 0)
- -0 (The number -0)
- 0n (The BigInt zero)
- '' (Empty string)
- null (The absense of a value)
- undefined (The undefined data type)
- NaN (Not a number)
Values that evaluate to a Boolean false
are said to be "falsy." All other values evaluate to a Boolean true
and are known as "truthy."
If the operand on the left of JavaScript's &&
operator evaluates to a Boolean false
, the value on the left is returned. If the operand on the left evaluates to a Boolean true
, the operand on the right is evaluated. If the operand on the right evaluates to a Boolean true
, the value on the right is returned.
In the above example, if the value of loggedIn
is false
, the statement will return false
and nothing will render. If loggedIn
is true
, the component on the right will render.
Using the &&
operator is a quick and easy way to conditionally render a component. Unlike using an if/else
statement, a switch
statement, or the ternary operator, using &&
doesn't provide a way to choose between 2 or more components to render.
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.