React Conditional Rendering

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

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

First, let's look at two components:

function UserGreeting(props) {
  return <h1>欢迎回来!</h1>;
}

function GuestGreeting(props) {
  return <h1>请先注册。</h1>;
}

We will create a Greeting component that displays one of them depending on whether the user is logged in:

React Example

function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />; } const root = ReactDOM.createRoot(document.getElementById("root")); root.render( //Try changing isLoggedIn={true}: <Greeting isLoggedIn={false} /> );

Try it »

Element Variables

You can use variables to store elements. This can help you conditionally render part of the component while the rest of the output does not change.

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

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

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 = <LogoutButton onClick={this.handleLogoutClick} />; } else { button = <LoginButton onClick={this.handleLoginClick} />; } return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> ); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <LoginControl /> );

Try it »

AND Operator &&

You can embed any expression in JSX by wrapping it in curly braces, including JavaScript's logical AND &&, which can conveniently 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']; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <Mailbox unreadMessages={messages} /> );

Try it »

In JavaScript,true && expressionalways returnsexpression, whilefalse && expression always returnsfalse。

Therefore, if the condition istrue,&&the element on the right will be rendered; if it isfalse, React will ignore and skip it.


Ternary Operator

Another method for conditional rendering is to use JavaScript's conditional operator:

condition ? true : false。

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

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}

It can also be used in larger expressions, although it is not very intuitive:

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

Preventing Component Rendering

In rare cases, you might want to hide a component even though it is rendered by another component. You can do this by having the render method return null instead of its render result.

In the following example,<WarningBanner />the component renders conditionally based on the value of the prop warn. If the value of warn is false, the component will 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> <WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}> {this.state.showWarning ? 'Hide' : 'Show'} </button> </div> ); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <Page /> );

Try it »

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

Other Extensions