Popular Searches
Popular Course Categories
Popular Courses

Conditional Rendering

Conditional Rendering

React Events and Conditional Rendering

Conditional Rendering in React JS – Complete Notes

Conditional Rendering is an important concept in React JS that allows developers to display different UI elements or components depending on a particular condition. It helps create dynamic and interactive applications by showing the appropriate content based on user actions, application state, props, authentication status, or data availability.

Course Link: JustAcademy React JS Training

Demo Link: Register for React JS Course Demo


1. What Is Conditional Rendering?

Conditional Rendering means displaying specific content only when a particular condition is satisfied. If the condition changes, React can render different content accordingly.

React uses standard JavaScript conditional techniques such as if, if...else, the ternary operator (? :), and the logical AND operator (&&) to control which JSX elements appear on the screen.

Example

function Greeting() {
  const isLoggedIn = true;
  if (isLoggedIn) {
    return <h1>Welcome Back!</h1>;
  }
  return <h1>Please Log In</h1>;
}
export default Greeting;

Explanation: When isLoggedIn is true, the component displays “Welcome Back!”. If it is false, it displays “Please Log In”.

2. Why Is Conditional Rendering Important?

  • Dynamic UI: Displays content according to the current application state.
  • User Authentication: Shows login forms or user dashboards based on login status.
  • Data Availability: Displays loading indicators, data, or error messages.
  • User Interaction: Shows or hides menus, forms, notifications, and dialogs.
  • Improved User Experience: Prevents irrelevant content from appearing.
  • Reusable Components: Allows a component to display different content based on its props.
  • Application Feedback: Shows success messages, warnings, and validation errors when needed.

3. Common Conditional Rendering Techniques

React supports several approaches to conditional rendering. The most suitable approach depends on whether you need to display one of two alternatives, show an optional element, or control the entire component output.

Technique Purpose Example
if Execute a condition before returning JSX. if (isLoggedIn) { ... }
if...else Choose between two blocks of content. if (isLoggedIn) { ... } else { ... }
Ternary operator Display one of two expressions inside JSX. {isLoggedIn ? "Welcome" : "Login"}
Logical AND (&&) Display content only when a condition is true. {isAdmin && <p>Admin</p>}
Logical OR (||) Provide a fallback value when the left side is falsy. {name || "Guest"}
Early return Return a specific result before the main JSX. if (loading) return <p>Loading...</p>;
null Render no UI from a component or expression. if (hidden) return null;

4. Conditional Rendering Using the if Statement

The if statement is useful when you need to check a condition and decide what JSX a component should return. It is particularly readable when the logic involves multiple statements.

Example: Checking Login Status

function LoginMessage() {
  const isLoggedIn = true;

  if (isLoggedIn) {
    return <h2>Welcome to Your Dashboard</h2>;
  }

  return <h2>Please Log In to Continue</h2>;
}
export default LoginMessage;

How It Works

  1. The isLoggedIn variable stores a Boolean value.
  2. The if statement checks whether the value is true.
  3. If true, React receives the dashboard greeting JSX.
  4. If false, execution reaches the second return statement.

Important: JavaScript's if statement cannot be inserted directly as a statement inside JSX curly braces. Use it in the component's JavaScript logic, or use an expression such as a ternary operator inside JSX.

5. Conditional Rendering Using if...else

The if...else statement is suitable when an application must display one of two different outputs.

Example: Pass or Fail Result

function Result() {
  const marks = 75;

  if (marks >= 40) {
    return <h2>Congratulations! You Passed.</h2>;
  } else {
    return <h2>Sorry, You Failed.</h2>;
  }
}
export default Result;

Explanation: When marks are 40 or higher, the component displays a passing message. Otherwise, it displays a failing message.

When to Use if...else

  • When the condition involves several statements.
  • When you want to return different component structures.
  • When the conditional logic is too complex for a short JSX expression.
  • When you want to keep rendering logic easy to read and maintain.

6. Conditional Rendering Using the Ternary Operator

The ternary operator is a compact way to choose between two expressions. It contains three parts: a condition, the expression used when the condition is true, and the expression used when it is false.

Syntax

condition ? expressionIfTrue : expressionIfFalse

Example: Login and Logout Buttons

function AuthButton() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn ? (
        <button>Logout</button>
      ) : (
        <button>Login</button>
      )}
    </div>
  );
}
export default AuthButton;

Explanation: If isLoggedIn is true, the Logout button appears. Otherwise, the Login button appears.

Example: Showing a Result Message

function StockStatus() {
  const inStock = false;

  return (
    <p>
      {inStock ? "Product Available" : "Out of Stock"}
    </p>
  );
}

Advantages of the Ternary Operator

  • It can be used directly inside JSX.
  • It keeps simple two-way conditions compact.
  • It can return text, elements, or components.
  • It is helpful for status labels, buttons, and short messages.

Best Practice: Avoid deeply nested ternary expressions. If several conditions are required, use if...else, a switch statement, or a clearly structured helper function.

7. Conditional Rendering Using the Logical AND Operator (&&)

The logical AND operator is commonly used when you want to display an element only if a condition is true. If the condition is false, React does not display a Boolean false value in the UI.

Syntax

{condition && <Component />}

Example: Displaying an Admin Message

function AdminPanel() {
  const isAdmin = true;

  return (
    <div>
      <h2>User Dashboard</h2>
      {isAdmin && <p>You have administrator access.</p>}
    </div>
  );
}
export default AdminPanel;

Explanation: The administrator message appears only when isAdmin is true. If it is false, the message is omitted.

Example: Showing a Notification

function Notification() {
  const hasNotification = true;

  return (
    <div>
      {hasNotification && (
        <p>You have a new notification!</p>
      )}
    </div>
  );
}

Important Warning About Zero

In JavaScript, the && operator returns an operand rather than always returning a Boolean. If the left side is the number 0, React can display that zero on the screen.

Incorrect example:

function MessageCount() {
  const count = 0;

  return (
    <div>
      {count && <p>You have new messages.</p>}
    </div>
  );
}

This example can display 0 instead of rendering nothing.

Correct example:

function MessageCount() {
  const count = 0;

  return (
    <div>
      {count > 0 && <p>You have new messages.</p>}
    </div>
  );
}

Using count > 0 produces a Boolean condition and avoids displaying the number zero accidentally.

8. Conditional Rendering Using the Logical OR Operator (||)

The logical OR operator can provide a fallback value when the value on its left side is falsy. It is useful for displaying default text when a name or label is missing.

Example

function UserProfile() {
  const userName = "";

  return (
    <h2>Welcome, {userName || "Guest"}!</h2>
  );
}
export default UserProfile;

Output: Welcome, Guest!

Note: The values "", 0, false, null, and undefined are falsy in JavaScript. If zero is a valid value that should be displayed, use a nullish coalescing expression (??) when the intention is to fall back only for null or undefined.

Example Using Nullish Coalescing

function ProductQuantity() {
  const quantity = 0;

  return (
    <p>Quantity: {quantity ?? 10}</p>
  );
}

Output: Quantity: 0

9. Conditional Rendering Using Element Variables

You can store JSX in a variable and assign different content to it depending on a condition. This technique is useful when you want to separate conditional logic from the main JSX structure.

Example

function AccountStatus() {
  const isVerified = true;
  let statusMessage;

  if (isVerified) {
    statusMessage = <p>Your account is verified.</p>;
  } else {
    statusMessage = <p>Please verify your account.</p>;
  }

  return (
    <section>
      <h2>Account Status</h2>
      {statusMessage}
    </section>
  );
}
export default AccountStatus;

Explanation: The variable statusMessage stores one of the two JSX elements. React renders the element assigned to that variable.

10. Conditional Rendering Using Early Returns

An early return allows a component to return immediately when a particular condition is met. It is often used for loading states, missing data, errors, and access restrictions.

Example: Loading State

function UserDetails() {
  const isLoading = true;

  if (isLoading) {
    return <p>Loading user details...</p>;
  }

  return <h2>User Details Loaded</h2>;
}
export default UserDetails;

Explanation: When isLoading is true, the component returns the loading message immediately. The remaining JSX is returned only when loading is false.

Example: Error and Data States

function Profile({ isLoading, error, user }) {
  if (isLoading) {
    return <p>Loading profile...</p>;
  }

  if (error) {
    return <p>Unable to load the profile.</p>;
  }

  if (!user) {
    return <p>No user information available.</p>;
  }

  return <h2>Welcome, {user.name}!</h2>;
}

This approach makes it easy to handle different application states without deeply nesting conditional expressions.

11. Conditional Rendering Using null

In React, a component can return null when it should render no visible UI. This is useful when an entire component should be hidden under a particular condition.

Example

function Warning({ showWarning }) {
  if (!showWarning) {
    return null;
  }

  return (
    <p>Warning: Please check your input.</p>
  );
}
export default Warning;

Explanation: If showWarning is false, the component returns null and displays nothing. If it is true, the warning appears.

Remember: Returning null hides the component's rendered output. It does not automatically remove the component's definition from your code.

12. Conditional Rendering with Props

Props allow a parent component to pass information to a child component. A child can use Boolean or other props to decide which content to render.

Example

function StatusMessage({ isOnline }) {
  return (
    <p>
      {isOnline ? "User is Online" : "User is Offline"}
    </p>
  );
}

function App() {
  return (
    <div>
      <StatusMessage isOnline={true} />
      <StatusMessage isOnline={false} />
    </div>
  );
}
export default App;

Explanation: The parent passes a different value to each instance of StatusMessage. Each component displays the appropriate status.

13. Conditional Rendering with State and Events

State allows a component to remember information between renders. When state changes, React can render the UI again so that it reflects the latest value. This makes state especially useful for showing and hiding elements in response to user interaction.

Example: Show and Hide Content

import { useState } from "react";

function ToggleContent() {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? "Hide Details" : "Show Details"}
      </button>

      {isVisible && (
        <p>These are the additional details.</p>
      )}
    </div>
  );
}
export default ToggleContent;

How It Works

  1. The useState(false) statement initializes isVisible to false.
  2. The button displays “Show Details” when the content is hidden.
  3. Clicking the button updates the state using setIsVisible.
  4. When the state becomes true, the details appear and the button label changes to “Hide Details”.
  5. Clicking the button again hides the details.

14. Conditional Rendering for Authentication

Applications often display different interfaces for authenticated and unauthenticated users. Conditional rendering can select the correct UI based on a login status supplied by the application's authentication logic.

Example

function Dashboard({ isLoggedIn }) {
  if (!isLoggedIn) {
    return (
      <div>
        <h2>Please Log In</h2>
        <button>Login</button>
      </div>
    );
  }

  return (
    <div>
      <h2>Dashboard</h2>
      <p>Welcome to your account.</p>
      <button>Logout</button>
    </div>
  );
}
export default Dashboard;

Important: Hiding a button or dashboard with conditional rendering is not a security mechanism. Sensitive data and protected operations must also be authorized by the server or backend.

15. Conditional Rendering for Loading, Success, and Error Messages

When an application requests data from an API, it commonly needs to display a loading indicator, a success result, or an error message. These are different UI states and can be handled with conditional rendering.

Example

function ApiResult({ status, data }) {
  if (status === "loading") {
    return <p>Loading data...</p>;
  }

  if (status === "error") {
    return <p>Something went wrong. Please try again.</p>;
  }

  if (status === "success") {
    return <p>Data loaded successfully: {data}</p>;
  }

  return <p>Waiting to start...</p>;
}
export default ApiResult;

Explanation: The status prop determines which message is displayed. The success branch uses the supplied data value.

16. Conditional Rendering Using a Switch Statement

A JavaScript switch statement can be useful when a component must handle several distinct values. You can use it to assign JSX to a variable and then render that variable.

Example

function OrderStatus({ status }) {
  let message;

  switch (status) {
    case "pending":
      message = <p>Your order is pending.</p>;
      break;
    case "shipped":
      message = <p>Your order has been shipped.</p>;
      break;
    case "delivered":
      message = <p>Your order has been delivered.</p>;
      break;
    default:
      message = <p>Order status is unavailable.</p>;
  }

  return <div>{message}</div>;
}
export default OrderStatus;

Explanation: The switch statement checks the value of status, selects the matching message, and stores it in message. React then renders that message.

17. Conditional Rendering in Lists

Conditional rendering can also be used when displaying lists of items. For example, an application can show a badge beside completed tasks or hide tasks that are already completed.

Example: Task List

const tasks = [
  { id: 1, title: "Learn JSX", completed: true },
  { id: 2, title: "Learn State", completed: false },
  { id: 3, title: "Practice React", completed: true }
];

function TaskList() {
  return (
    <ul>
      {tasks.map((task) => (
        <li key={task.id}>
          {task.title}
          {task.completed && " - Completed"}
        </li>
      ))}
    </ul>
  );
}
export default TaskList;

Explanation: Each task is rendered using map(). The “Completed” label appears only when task.completed is true. A unique key helps React identify each list item.

18. Conditional Styling in React

Conditional rendering concepts can also determine which CSS class or inline style is applied to an element. This is useful for changing colors or appearance based on a status.

Example: Online and Offline Status

function UserStatus({ isOnline }) {
  return (
    <p className={isOnline ? "online" : "offline"}>
      {isOnline ? "Online" : "Offline"}
    </p>
  );
}
export default UserStatus;

Example CSS

.online {
  color: green;
  font-weight: bold;
}

.offline {
  color: gray;
  font-weight: normal;
}

The class name changes depending on the value of isOnline. Define the corresponding CSS classes in your stylesheet.

19. Conditional Rendering vs. Hiding with CSS

Conditional Rendering CSS Hiding
Can omit an element from the rendered React output. Can keep an element in the DOM while making it invisible.
Uses conditions such as if, &&, and ? :. Uses styles such as display or visibility.
Useful when content should be present only in certain states. Useful when the element should remain mounted but be visually hidden.
Can affect whether a component remains mounted and whether its local state is preserved. Usually keeps the component mounted, so its local state remains.

20. Common Mistakes in Conditional Rendering

Mistake 1: Using if Directly Inside JSX

Incorrect:

return (
  <div>
    {if (isLoggedIn) {
      <p>Welcome</p>
    }}
  </div>
);

Correct: Use a ternary expression inside JSX, or handle the condition before the return statement.

return (
  <div>
    {isLoggedIn ? <p>Welcome</p> : <p>Please log in</p>}
  </div>
);

Mistake 2: Forgetting the False Branch

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

The ternary operator requires both expressions separated by a colon. Use && instead when you only need to render something for a true condition.

Mistake 3: Displaying Zero Unexpectedly

{items.length && <p>Items available</p>}

If items.length is zero, React can display the number 0. Prefer items.length > 0 && ....

Mistake 4: Using Too Many Nested Ternary Operators

Deeply nested ternary expressions can make code difficult to read. Use early returns, a switch statement, or a helper function for complex conditions.

Mistake 5: Confusing State with a Regular Variable

Changing a normal local variable does not itself trigger a React re-render. If the UI needs to respond to user actions, use React state or another appropriate reactive data source.

Mistake 6: Treating UI Visibility as Authorization

Conditionally hiding sensitive controls does not prevent a user from calling a backend endpoint directly. Authorization must be enforced on the server.

21. Best Practices for Conditional Rendering

  • Use if...else or early returns for complex conditions.
  • Use the ternary operator for simple two-way choices.
  • Use && when a single element should appear only if a condition is true.
  • Check numeric conditions explicitly to avoid displaying zero accidentally.
  • Use meaningful Boolean names such as isLoading, isLoggedIn, and hasError.
  • Keep JSX expressions short and readable.
  • Use state for values that must trigger a UI update when changed.
  • Handle loading, empty, success, and error states when displaying API data.
  • Use unique keys when rendering lists of conditional elements.
  • Do not rely on conditional rendering alone to protect private data.

22. Practical Project: Student Result Dashboard

This mini project demonstrates conditional rendering with a student's marks, pass/fail status, and a conditional result message.

Complete Code

function StudentResult() {
  const student = {
    name: "Rahul",
    marks: 78,
    isSubmitted: true
  };

  if (!student.isSubmitted) {
    return (
      <div>
        <h2>Student Result</h2>
        <p>Result has not been submitted yet.</p>
      </div>
    );
  }

  return (
    <div>
      <h2>Student Result Dashboard</h2>
      <p>Name: {student.name}</p>
      <p>Marks: {student.marks}</p>
      <p>
        Result: {student.marks >= 40 ? "Pass" : "Fail"}
      </p>
      {student.marks >= 75 && (
        <p>Excellent performance!</p>
      )}
    </div>
  );
}
export default StudentResult;

Project Explanation

  1. The student object contains the student's name, marks, and submission status.
  2. The early return displays a message if the result has not been submitted.
  3. The ternary operator determines whether the student has passed or failed.
  4. The logical AND operator displays an additional message for marks of 75 or higher.
  5. Changing the student data changes which messages are rendered.

Practice Extensions

  • Add a “Needs Improvement” message for marks below 40.
  • Display “Distinction” for marks of 90 or higher.
  • Show a loading message while the result is being fetched.
  • Display an error message when the result is unavailable.
  • Use React state to let a user toggle the result details.

23. Conditional Rendering Interview Questions and Answers

Q1. What is conditional rendering in React?

Conditional rendering is the technique of displaying different UI elements or components based on conditions, props, state, or data.

Q2. Which JavaScript techniques can be used for conditional rendering?

Common techniques include if, if...else, the ternary operator, logical AND (&&), logical OR (||), switch statements, and early returns.

Q3. What is the difference between if...else and the ternary operator?

if...else is a JavaScript statement that is useful for more involved control flow. The ternary operator is an expression that can be placed directly inside JSX to select between two alternatives.

Q4. When should you use the logical AND operator?

Use && when an element should be rendered only when a condition is true and no alternative content is needed when the condition is false.

Q5. Why can zero appear when using &&?

Because JavaScript returns the left operand when it is falsy. If that operand is the number zero, React can render the zero. Use a Boolean comparison such as count > 0.

Q6. What does returning null do in React?

Returning null means the component renders no visible UI for that render.

Q7. Can conditional rendering depend on props?

Yes. A component can receive props from its parent and use their values to determine which content to render.

Q8. Can conditional rendering depend on state?

Yes. When state changes, React can re-render the component and show content appropriate to the new state.

Q9. What is an early return?

An early return exits a component function before its main JSX is returned. It is often used to handle loading, errors, missing data, or access restrictions in the UI.

Q10. Is conditional rendering a security feature?

No. It controls what appears in the interface. Sensitive data and protected operations must be secured by appropriate backend authorization.

24. Practice Exercises

  1. Create a component that displays “Good Morning” or “Good Evening” based on a Boolean prop.
  2. Use a ternary operator to show “Available” or “Unavailable” for a product.
  3. Use && to display a warning when a form has validation errors.
  4. Use an early return to display a loading message before showing user details.
  5. Create a show/hide button using useState.
  6. Use a switch statement to display different order status messages.
  7. Render a list of tasks and display a completion label for finished tasks.
  8. Handle loading, empty, success, and error states in a sample API result component.

25. Quick Revision Checklist

  • Understand what conditional rendering means.
  • Know how to use if and if...else.
  • Understand the syntax and use of the ternary operator.
  • Know how to render optional elements with &&.
  • Understand fallback expressions with || and ??.
  • Know how element variables and early returns work.
  • Understand how props and state influence the UI.
  • Avoid the accidental rendering of zero with &&.
  • Practice rendering loading, success, empty, and error states.
  • Understand the difference between hiding UI and securing data.

26. Conclusion

Conditional Rendering is a fundamental React JS concept that makes applications dynamic, responsive, and interactive. By understanding if...else, the ternary operator, logical AND, logical OR, element variables, and early returns, developers can display the correct content for different application states. Practicing these techniques with forms, dashboards, authentication interfaces, lists, and API responses will help you build clear and maintainable React applications.

To learn more about React JS and related practical topics, visit JustAcademy React JS Training or register for a React JS course demo.

Additional Learning Resource: Official React Documentation – Conditional Rendering.

Previous Next
whatsapp