SoFunction
Updated on 2025-04-07

Detailed explanation of how to perform conditional rendering in React

introduction

In modern web development, React, as a popular JavaScript library, provides developers with a way to efficiently build user interfaces. Conditional rendering is a key concept in React, which allows us to dynamically display or hide components based on different conditions, thereby increasing application flexibility and user experience.

This article will dive into how to implement conditional rendering in React and demonstrate common usage with sample code.

What is conditional rendering?

Conditional rendering refers to when to render a component or element based on whether certain conditions are true. In React, we can implement conditional rendering through JavaScript's logical operators, conditional statements, and even ternary operators.

Basic examples

First, let's start with a simple example that demonstrates how to conditionally render components based on state values.

import React, { useState } from 'react';

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const handleLogin = () => {
    setIsLoggedIn(true);
  }

  const handleLogout = () => {
    setIsLoggedIn(false);
  }

  return (
    <div>
      {isLoggedIn ? (
        <div>
          <h1>Welcome back!</h1>
          <button onClick={handleLogout}>quit</button>
        </div>
      ) : (
        <div>
          <h1>Please log in</h1>
          <button onClick={handleLogin}>Log in</button>
        </div>
      )}
    </div>
  );
}

export default App;

In this simple example, we useuseStateHook to manage user login status,isLoggedInThe state is initiallyfalse. Based on this state, we use the ternary operator to conditionally render different content. If the user is already logged in, we will display the welcome message and the login button; otherwise, the login prompt and the login button will be displayed.

Use logic and operators (&&)

In addition to the ternary operator, we can also use logic and operators to implement conditional rendering. This is especially useful when we only want to render a part of the content when a certain condition is true.

import React, { useState } from 'react';

function App() {
  const [showMessage, setShowMessage] = useState(false);

  return (
    <div>
      <button onClick={() => setShowMessage(!showMessage)}>Switch messages</button>
      {showMessage && <h1>The message has been displayed!</h1>}
    </div>
  );
}

export default App;

In this example, clicking the button will switchshowMessagestatus. whenshowMessagefortrueWhen rendering<h1> message is displayed! </h1>, otherwise no content will be rendered.

Use conditional statement

Sometimes, conditional rendering involves multiple conditions. In this case, it is possible to useif...elseStatements to implement more complex logic. Let's see a useif...elseExample:

import React, { useState } from 'react';

function App() {
  const [userRole, setUserRole] = useState('guest');

  const renderContent = () =&gt; {
    if (userRole === 'admin') {
      return &lt;h1&gt;welcome,administrator!&lt;/h1&gt;;
    } else if (userRole === 'user') {
      return &lt;h1&gt;welcome,user!&lt;/h1&gt;;
    } else {
      return &lt;h1&gt;welcome,Visitors!&lt;/h1&gt;;
    }
  };

  return (
    &lt;div&gt;
      {renderContent()}
      &lt;button onClick={() =&gt; setUserRole('admin')}&gt;登录为administrator&lt;/button&gt;
      &lt;button onClick={() =&gt; setUserRole('user')}&gt;登录为user&lt;/button&gt;
      &lt;button onClick={() =&gt; setUserRole('guest')}&gt;登录为Visitors&lt;/button&gt;
    &lt;/div&gt;
  );
}

export default App;

In this example, we define arenderContentFunction, according touserRoleDifferent values ​​of the state determine which segment of content is rendered. When the user clicks a button, it will be updateduserRole,andrenderContentIt will be called again to update the rendered content.

Conditional rendering in the list

Sometimes we need to perform conditional rendering when rendering a list. This can be donemapFunction and conditional logic are implemented in combination. Here is an example:

import React from 'react';

function App() {
  const items = [
    { id: 1, name: 'Item 1', available: true },
    { id: 2, name: 'Item 2', available: false },
    { id: 3, name: 'Item 3', available: true },
  ];

  return (
    &lt;ul&gt;
      {(item =&gt; (
        &lt;li key={}&gt;
          {} { ? '(Available)' : '(Sold out)'}
        &lt;/li&gt;
      ))}
    &lt;/ul&gt;
  );
}

export default App;

In this example, we iterate over a list of items and render the text based on the available status conditions for each item. Attach the instructions “(available)” after available items, and “(sold out)” after sold out items.

Summarize

Conditional rendering is an important aspect of building dynamic and interactive user interfaces. In React, we can easily implement conditional rendering in a variety of ways, such as ternary operators, logical operators, and conditional statements. By using these technologies rationally, developers can provide users with a better experience.

In actual development, reasonable use of conditional rendering will improve the readability and maintenance of the code. At the same time, be careful to avoid overly complex conditional nesting, which may make components difficult to understand. By building clear conditional rendering logic, your React application can be made more vivid and flexible.

The above is a detailed explanation of how to perform conditional rendering in React. For more information about React performing conditional rendering, please pay attention to my other related articles!