Course: Section

Get Started with Modern React: Step by Step

Episode: Title

S02・V13: Conditional Rendering (Part 2)

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

Objectives
  1. We will show you how to render elements conditionally using the conditional operator.
  2. We will show you how a component can hide itself even though it was rendered by another component.
  3. We will show you how to import styles from a CSS file.
Watch Video
Duration: 7m 11s

Conditional Operator

Another method for conditionally rendering elements inline is to use the JavaScript “conditional operator”, which gives us a “ternary expression”.

We will use a ternary expression to conditionally render a small block of text. Let’s render a LoginControl, similar to what we did in the previous video.

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

Now, we will define the LoginControl component, which has state of isLoggedIn. Return some JSX from the component showing some text.

src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";

const LoginControl = () => {
  const [isLoggedIn, setLoggedIn] = useState(false);

  return (
    <diiv>
      The user is logged in.
    </dv>
  );
};

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

Now, we will use a ternary expression to show the logged-in state of the user.

src/index.js
const LoginControl = () => {
  const [isLoggedIn, setLoggedIn] = useState(false);

  return (
    <div>
      The user is <b>{isLoggedIn ? "currently" : "not"}</b> logged in.    </div>
  );
};

It can also be used for larger expressions, although it is less obvious what is going on.

src/index.js
const LoginControl = () => {
  const [isLoggedIn, setLoggedIn] = useState(false);

  return (
    <div>
      {isLoggedIn ? (        <button onClick={() => setLoggedIn(false)}>Logout</button>      ) : (        <button onClick={() => setLoggedIn(true)}>Login</button>      )}    </div>
  );
};

Just like in JavaScript, it is up to you to choose an appropriate style based on what you and your team consider more readable. Also remember that whenever conditions become too complex, it might be a good time to extract a component.

Preventing a Component from Rendering

In rare cases, you might want a component to hide itself, even though it was rendered by another component. To do this, return null instead of its normally rendered output.

As an example, let’s render a Page component. Let’s start defining the Page component. This component will toggle a warning. We will keep track of, and update, the showWarning state. We will return a WarningBanner component, which we will define shortly. And, we will render a button, which will change its text depending on the showWarning state.

src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";

const Page = props => {
  const [showWarning, setShowWarning] = useState(true);

  return (
    <div>
      <WarningBanner warn={showWarning} />
      <button>
        {showWarning ? "Hide" : "Show"}
      </button>
    </div>
  );
};

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

We will give this button an onClick prop, and pass in the reference to a handler: <button onClick={handleToggleClick}>. The handler will toggle the state of showWarning.

  const handleToggleClick = event => {
    setShowWarning(!showWarning);
  };

Now, we will define the WarningBanner component.

const WarningBanner = props => {
  if (!props.warn) {
    return null;
  }
  return <div className="warning">Warning!</div>;
};

We will return null if the boolean value of the warn prop is not true. Otherwise, we will show a warning.

src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";

const WarningBanner = props => {
  if (!props.warn) {
    return null;
  }
  return <div className="warning">Warning!</div>;
};

const Page = props => {
  const [showWarning, setShowWarning] = useState(true);

  const handleToggleClick = event => {
    setShowWarning(!showWarning);
  };

  return (
    <div>
      <WarningBanner warn={showWarning} />
      <button onClick={handleToggleClick}>
        {showWarning ? "Hide" : "Show"}
      </button>
    </div>
  );
};

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

Adding CSS Styling

Let’s add some CSS styling to the warning.

First, we will create an index.css file in the src/ folder. Switch over to the Terminal app, and shut down the local development server. Now, create an index.css file using the touch command.

touch src/index.css

Restart the local development server.

yarn start

We can now return to our index.js file in Atom. Import the CSS file after our React and ReactDOM imports. This will allow us to use any CSS styles in the index.css file. The build toolchain “Create React App” will take care of loading CSS files properly.

src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./index.css";
const WarningBanner = props => {
  if (!props.warn) {
    return null;
  }
  return <div className="warning">Warning!</div>;
};

const Page = props => {
  const [showWarning, setShowWarning] = useState(true);

  const handleToggleClick = event => {
    setShowWarning(!showWarning);
  };

  return (
    <div>
      <WarningBanner warn={showWarning} />
      <button onClick={handleToggleClick}>
        {showWarning ? "Hide" : "Show"}
      </button>
    </div>
  );
};

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

Now, let’s move to the index.css file.

First, let’s add some body styling. We will use a sans-serif font-family. Set the margin to zero. Now, we will add styles to the warning class. Set the background-color to red. Align the text to the center with the text-align attribute. Make the width 100%. Set the padding to 10 pixels. Set the font-size to 14 points. Make the text color white.

src/index.css
body {
  font-family: sans-serif;
  margin: 0;
}

.warning {
  background-color: red;
  text-align: center;
  width: 100%;
  padding: 10px;
  font-size: 14pt;
  color: white;
}

Test it in the browser.

Summary

We showed you how to render elements conditionally using the conditional operator. We showed you how a component can hide itself even though it was rendered by another component. And, we showed you how to import styles from a CSS file.

Next Up…

In the next video, we will talk about rendering lists of elements, and explain why keys are important in React.