Introduction

With React, we can build Single Page Applications that are dynamic and highly interactive. One way we fully utilize such interactivity is through conditional rendering.

Conditional rendering as a term describes the ability to render different UI markup based on certain conditions. In React-speak, it is a way to render different elements or components based on a condition. This concept is applied often in the following scenarios:

  • Rendering external data from an API
  • Showing/hiding elements
  • Toggling application functionality
  • Implementing permission levels
  • Authentication and Authorization

In this article, we examine seven(7) ways to implement such conditional rendering in React applications.

The Challenge

As a challenge, based on the value of isLoggedIn in our component state, we want to be able to display a Login button if the user isn’t logged in, and a Logout button if he/she is.

This is what our starter component looks like:

Visually:

Code:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoggedIn: true
    };
  }
  render() {
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        <button>Login</button>
        <button>Logout</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Copy

Bear in mind that  … within the code snippets implies that some code which isn’t directly connected with the point being explained goes there.

#react

7 Ways to Implement Conditional Rendering in React Applications
1.60 GEEK