ReactJS Foundations

Listing 3-10: Conditional Rendering with &&

Previous Listing | Next Listing
Note: if you don't see the welcome messsage, you're not logged in.
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.

React JS Foundations

Latest Blog Posts

React Router v6 Code Posted

Chapter 12 covers how to do Routing in React using React Router v5. In the time since the book came out, React Router v6 has been released, which includes some changes to how it’s used. I’m also working on writing a version of Chapter 12 that covers React Router 6. I’ll post that to the […]

Read More >

Errata: Chapter 6

The final code example in the Shallow Copies and the Spread Operator section on page 160 shows a rest parameter with only two periods. There should be three. The correct code is:

Read More >

React 18 Update

The biggest change in React 18 is the addition of concurrent rendering. With concurrent rendering, you can mark state updates as non-urgent in order to improve the performance of your user interface. Concurrent rendering is opt-in. What this means is that it’s only enabled when you use a concurrent feature. As a result, apps built […]

Read More >