ReactJS Foundations

Listing 3-9: Conditional Rendering with Element Variables

Previous Listing | Next Listing

import Header from './Header';
import Login from './Login';

function Welcome({loggedIn}) {
  let header;

  if (loggedIn) {
    header = <Header />;
  } else {
    header = <Login />;
  }
  return (
      <div>
        {header}
      </div>
  )
}
        
export default Welcome;

Conditional Rendering with Element Variables

Outside of the return statement, create a variable to hold the element you want to render conditionally. You can then use an if/else statement to assign different elements to the variable based on any condition. In this example, the Boolean isLoggedIn is passed to the component as a prop and a different component is assigned to the header variable based on whether isLoggedIn is true or false. The final step is to render the header variable inside the return statement.

The benefit of using this method for conditional rendering is that it's easy to read, and you can have as many branches as you need.

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 >