Conditional Rendering in JSX: Dynamic Component Creation

In React.js, JSX syntax achieves dynamic rendering through conditional expressions, with core logic based on the { condition ? component : fallback } structure. Developers can control the display and hiding of components using v-if, v-else, or the ternary operator. For example:

{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in</p>}

The logic for conditional rendering judgment relies on JavaScript boolean value conversion; values such as false, 0, and null are treated as "false", while true, non-empty strings, and other truthy values are treated as "true". This mechanism allows developers to dynamically switch component content based on business logic.

Dynamic Component Construction

JSX syntax supports building components dynamically through conditional expressions, enabling "rendering on demand." Developers can use the { condition ? <ComponentA /> : <ComponentB /> } structure to render different components based on state or data. For example:

{user.role === 'admin' ? <AdminPanel /> : <Dashboard />}

The key to dynamic component construction lies in state management, such as using useState or useEffect to control rendering logic. For instance, when a user clicks a button, the state is switched to render different components, achieving flexible switching of functional modules.

Examples

Conditional Rendering Example

function App() {
  const [darkMode, setDarkMode] = useState(false);

  return (
    <div className={darkMode ? 'dark' : ''}>
      {darkMode ? <h1>Dark mode enabled</h1> : <h1>Light mode enabled</h1>}
      <button onClick={() => setDarkMode(!darkMode)}>
        {darkMode ? 'Switch to dark mode' : 'Switch to light mode'}
      </button>
    </div>
  );
}

Dynamic Component Example

function App() {
  const [isPremium, setIsPremium] = useState(false);

  return (
    <div>
      {isPremium ? (
        <div>You have purchased premium features</div>
      ) : (
        <div>Please purchase a membership to unlock features</div>
      )}
      <button onClick={() => setIsPremium(!isPremium)}>
        {isPremium ? 'Cancel membership' : 'Become a member'}
      </button>
    </div>
  );
}

Summary

Conditional rendering and dynamic component construction in JSX syntax are core features of React.js, achieving flexible component switching through concise conditional expressions. Developers must understand the rules for boolean value conversion and reasonably use state management to control rendering logic. In practice, attention should be paid to the performance impact of conditional judgments to avoid rendering overhead caused by excessive nesting.