0
0
Reactframework~5 mins

If conditions in JSX in React

Choose your learning style9 modes available
Introduction

If conditions in JSX help you show or hide parts of your webpage based on some rules, like showing a message only if a user is logged in.

Show a welcome message only when a user is logged in.
Display a loading spinner while data is being fetched.
Hide a button if a form is not filled correctly.
Show different text based on a user's choice.
Syntax
React
const element = condition ? <ComponentA /> : <ComponentB />;

You can use the ternary operator inside JSX to choose what to show.

For simple show/hide, you can use && to show something only if a condition is true.

Examples
Shows a welcome message if logged in, otherwise asks to log in.
React
const message = isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>;
Shows "Loading..." only if isLoading is true.
React
const loading = isLoading && <p>Loading...</p>;
Renders AdminPanel if user is admin, else UserPanel.
React
return (
  <div>
    {isAdmin ? <AdminPanel /> : <UserPanel />}
  </div>
);
Sample Program

This component shows a welcome message if the user is logged in. A button toggles the login state to show how the message changes.

React
import React, { useState } from 'react';

export default function Greeting() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <div>
      <h1>My Website</h1>
      {isLoggedIn ? <p>Welcome back, friend!</p> : <p>Please log in to continue.</p>}
      <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
        {isLoggedIn ? 'Log out' : 'Log in'}
      </button>
    </div>
  );
}
OutputSuccess
Important Notes

Use parentheses around JSX inside conditions for better readability.

Don't use if statements directly inside JSX; use ternary or && instead.

Summary

If conditions in JSX let you show different things based on rules.

Use ternary (condition ? A : B) for two choices.

Use && to show something only if a condition is true.