ReactJS Tutorial for Beginners - 12 - Conditional Rendering


In this chapter, we will learn how to render elements/components in React based on some condition. In other words, based on one or several conditions, a component decides which elements it will return.

In React, conditional rendering works the same way as the conditions work in JavaScript. We use JavaScript operators to create elements representing the current state, and then React Component update the UI to match them.

There is more than one way to do conditional rendering in React. Let's discuss all of them with an example.

1. if-else Approach

This example renders a different greeting depending on the value of isLoggedIn prop.
Consider these two components:
function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}
We’ll create a Greeting component that displays either of these components depending on whether a user is logged in:
function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />,
  document.getElementById('root')
);

2. Element Variables Approach

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 these two new components representing Logout and Login buttons:
function LoginButton(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

function LogoutButton(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}
In the example below, we will create a stateful component called LoginControl.
It will render either or depending on its current state:
class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;
    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
        {button}
      </div>
    );
  }
}

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);
While declaring a variable and using an if statement is a fine way to conditionally render a component, sometimes you might want to use a shorter syntax. 
Let's discuss a few ways to inline conditions in React JSX.

3. Inline If with Logical && Operator

You may embed expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical && operator. It can be handy for conditionally including an element:
import React, { Component } from 'react'

class UserGreeting extends Component {
  constructor(props) {
    super(props)

    this.state = {
      isLoggedIn: true
    }
  }

  // #short-circuit-operator-approach
  render() {
    return this.state.isLoggedIn && <div>Welcome Ramesh</div>
  }
}

export default UserGreeting
It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

4. Ternary Operator Approach

Another method for conditionally rendering elements inline is to use the JavaScript conditional operator condition? true: false.
In the example below, we use it to conditionally render a small block of text.
import React, { Component } from 'react'

class UserGreeting extends Component {
  constructor(props) {
    super(props)

    this.state = {
      isLoggedIn: true
    }
  }

  // ternary-operator-approach
  render() {
    return this.state.isLoggedIn ? (
      <div>Welcome Ramesh</div>
    ) : (
      <div>Welcome Guest</div>
    )
  }
}

export default UserGreeting

What's Next?

In this chapter, we have learned how to render elements/components in React based on some condition with an example.

Comments