Easy Tutorial
❮ React Component Life Cycle React Tutorial ❯

React Conditional Rendering

In React, you can create different components to encapsulate various behaviors you need. You can also render only some of them based on the state of your application.

Conditional rendering in React works the same way as conditions 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.

Let's look at two components:

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}

We will create a Greeting component that displays either of these components based on whether a user is logged in:

React Example

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

ReactDOM.render(
  // Try changing isLoggedIn={true}:
  &lt;Greeting isLoggedIn={false} />,
  document.getElementById('example')
);

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.

In the following example, we will create a stateful component called LoginControl.

It will render either <LoginButton /> or <LogoutButton /> based on its current state, and it will also render the <Greeting /> from the previous example.

React Example

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 = null;
    if (isLoggedIn) {
      button = &lt;LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = &lt;LoginButton onClick={this.handleLoginClick} />;
    }

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

ReactDOM.render(
  <LoginControl />,
  document.getElementById('example')
);

Logical && Operator

You can embed any expressions in JSX by wrapping them in curly braces, including JavaScript's logical &&, which can be conveniently used to conditionally render an element.

React Example

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  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(
  &lt;Mailbox unreadMessages={messages} />,
  document.getElementById('example')
);
ReactDOM.render(
  &lt;Mailbox unreadMessages={messages} />,
  document.getElementById('example')
);

In JavaScript, true && expression always returns expression, while false && expression always returns false.

Therefore, if the condition is true, the element to the right of && will be rendered; if it is false, React will ignore and skip it.


Ternary Operator

Another method for conditionally rendering elements is by using the JavaScript ternary operator:

condition ? true : false

In the following example, we use it to conditionally render a small block of text.

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        &lt;LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        &lt;LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}

Preventing Component from Rendering

In rare cases, you might want to hide a component even if it was rendered by another component. Returning null instead of its render output will achieve this.

In the following example, <WarningBanner /> is rendered based on the value of the warn prop. If the value of warn is false, the component does not render:

React Example

function WarningBanner(props) {
  if (!props.warn) {
    return null;
  }

  return (
    <div className="warning">
      Warning!
    </div>
  );
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {showWarning: true}
    this.handleToggleClick = this.handleToggleClick.bind(this);
  }

  handleToggleClick() {
    this.setState(prevState => ({
      showWarning: !prevState.showWarning
    }));
  }

  render() {
    return (
      <div>
        &lt;WarningBanner warn={this.state.showWarning} />
        &lt;button onClick={this.handleToggleClick}>
          {this.state.showWarning ? 'Hide' : 'Show'}
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <Page />,
  document.getElementById('example')
);

Returning null from a component's render method does not affect the firing of the component's lifecycle methods. For example, componentWillUpdate and componentDidUpdate will still be called.

❮ React Component Life Cycle React Tutorial ❯