Course: Section

Get Started with Modern React: Step by Step

Episode: Title

S02・V12: Conditional Rendering (Part 1)

Date Created: July 17th, 2019
Last Updated: 27 days ago

Objectives
  1. We will show you how to render elements conditionally using “if”.
  2. We will show you an example of using a variable to store elements to help conditional rendering.
  3. We will show you how to use the logical “&&” operator.
Watch Video
Duration: 7m 46s

Conditional Rendering

In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if, or the conditional operator, to create elements representing the current state, and let React update the UI to match them.

We will first add a UserGreeting component.

const UserGreeting = props => {
  return <h1>Welcome back!</h1>;
};

And a GuestGreeting component.

const GuestGreeting = props => {
  return <h1>Please sign up.</h1>;
};

Let’s import react and react-dom at the top of the file.

import React, { useState } from "react";
import ReactDOM from "react-dom";

const UserGreeting = props => {
  return <h1>Welcome back!</h1>;
};

const GuestGreeting = props => {
  return <h1>Please sign up.</h1>;
};

Next, we’ll create a Greeting component that displays either of the components depending on whether a user is logged in. This component will have an isLoggedIn property. We will destructure isLoggedIn from props, which is commonly done in React. And now, we will add an if condition.

const Greeting = props => {
  const { isLoggedIn } = props;

  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
};

Let’s render the Greeting component to the DOM. We will pass the isLoggedIn prop as false.

import React, { useState } from "react";
import ReactDOM from "react-dom";

const UserGreeting = props => {
  return <h1>Welcome back!</h1>;
};

const GuestGreeting = props => {
  return <h1>Please sign up.</h1>;
};

const Greeting = props => {
  const { isLoggedIn } = props;

  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
};

ReactDOM.render(
  <Greeting isLoggedIn={false} />,
  document.getElementById("root")
);

If we pass true to the isLoggedIn prop of Greeting, then we get:

ReactDOM.render(
  <Greeting isLoggedIn={true} />,  document.getElementById("root")
);

This example renders a different greeting depending on the value of isLoggedIn prop.

Element Variables

You can use variables to store elements. This can help you conditionally render a part of the component while the rest of the output doesn’t change.

Consider two new components that represent Login and Logout buttons. First, the Login button.

const LoginButton = props => {
  return <button onClick={props.onClick}>Login</button>;
};

Next, the Logout button.

const LogoutButton = props => {
  return <button onClick={props.onClick}>Logout</button>;
};

Next, we will create a stateful function component called LoginControl. It will render either a LoginButton or a LogoutButton and a greeting depending on its current state.

const LoginControl = () => {};

We will render this LoginControl to the DOM.

ReactDOM.render(
  <LoginControl />,
  document.getElementById("root")
);

Within the LoginControl component, we will add the isLoggedIn state getter and setter, with the initial state being false. Next, we will define a button variable. We will assign the LogoutButton to the button if the state isLoggedIn is true. Otherwise, we will assign the LoginButton to the button. Then, we will return the Greeting, and the button under it.

import React, { useState } from "react";
import ReactDOM from "react-dom";

const UserGreeting = props => {
  return <h1>Welcome back!</h1>;
};

const GuestGreeting = props => {
  return <h1>Please sign up.</h1>;
};

const Greeting = props => {
  const { isLoggedIn } = props;

  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
};

const LoginButton = props => {
  return <button onClick={props.onClick}>Login</button>;
};

const LogoutButton = props => {
  return <button onClick={props.onClick}>Logout</button>;
};

const LoginControl = () => {
  const [isLoggedIn, setLoggedIn] = useState(false);  let button;  if (isLoggedIn) {    button = <LogoutButton onClick={() => setLoggedIn(false)} />;  } else {    button = <LoginButton onClick={() => setLoggedIn(true)} />;  }  return (    <div>      <Greeting isLoggedIn={isLoggedIn} />      {button}    </div>  );};

ReactDOM.render(
  <LoginControl />,
  document.getElementById("root")
);

Save the file and try it out in the browser.

Inline Conditions

Sometimes you might want to use a shorter syntax. There are a few ways to inline conditions in JSX.

You may embed any expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical && operator. It can be handy for conditionally including an element.

Let’s add a Mailbox component, which shows you how many unread messages you have. We will destructure the unreadMessages prop from the props object. Next, we will return some JSX.

const Mailbox = props => {
  const { unreadMessages } = props;

  return (
    <div>
      <h1>Hello!</h1>
    </div>
  );
};

Now, we will hard-code a messages array.

const messages = ["React", "Re: React", "Re:Re: React"];

Under the h1 header, we will add a JavaScript expression in a JSX container. It will have a condition, which checks if the length of the unreadMessages is larger than zero: unreadMessages.length > 0. We will follow the condition with a logical &&. Then we will add an element, which is an h2 header with some text inside.

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Mailbox = props => {
  const { unreadMessages } = props;

  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 && (        <h2>          You have {unreadMessages.length} unread messages.        </h2>      )}    </div>
  );
};

const messages = ["React", "Re: React", "Re:Re: React"];

ReactDOM.render(
  <Mailbox unreadMessages={messages} />,  document.getElementById("root")
);

The logical && operator works as follows:

  • If the condition is true, then the element renders.
  • If the condition is false, then the element does not render.

Summary

We showed you how to render elements conditionally using if. We showed you an example of using a variable to store elements to help conditional rendering. Also, we showed you how to use the logical && operator.

Next Up…

In the next video, we will continue talking about conditional rendering.