Projects

What is Conditional Rendering?

In React, conditional rendering means showing (or hiding) something on the screen based on certain conditions. For example, you might want to show a message like "Welcome back!" if a user is logged in, but show a "Please log in" message if they’re not logged in. It’s like making decisions in your app: "If this happens, show this; otherwise, show that."

How Conditional Rendering Works in React

React lets you use JavaScript logic to conditionally render things inside your components. This means you can use if, else, ternary operators, or even JavaScript functions to decide what should appear in the user interface (UI). Let’s break down each way of doing this.

1. Using if Statements

In JavaScript, if statements allow you to run some code only if a condition is true. You can use this inside a React component to decide what to render.


import React from 'react';

const ConditionalRenderingExample = () => {
  const isLoggedIn = true;  // This is the condition (true or false)

  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please log in.</h1>;
  }
};

export default ConditionalRenderingExample;
      

In this example, we have a variable called isLoggedIn that holds a boolean value (either true or false). If isLoggedIn is true, React will display "Welcome back!". If isLoggedIn is false, React will display "Please log in."

2. Using Ternary Operator

Another way to do conditional rendering is with the ternary operator. It’s a shorthand for if...else. Here’s how it works:


import React from 'react';

const ConditionalRenderingExample = () => {
  const isLoggedIn = false;

  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
    </div>
  );
};

export default ConditionalRenderingExample;
      

The ternary operator checks if isLoggedIn is true. If true, it displays "Welcome back!". If false, it displays "Please log in." This approach is shorter and useful for simple conditions.

3. Using && (Logical AND)

The && operator renders content only when a condition is true, without an else case. Here’s an example:


import React from 'react';

const ConditionalRenderingExample = () => {
  const hasNewMessages = true;

  return (
    <div>
      <h1>Welcome to your dashboard</h1>
      {hasNewMessages && <p>You have new messages!</p>}
    </div>
  );
};

export default ConditionalRenderingExample;
      

If hasNewMessages is true, it shows "You have new messages!". Otherwise, nothing is shown.

4. Using Functions for Conditional Rendering

You can also use functions to handle complex conditional rendering. This can make your code more readable:


import React from 'react';

const ConditionalRenderingExample = () => {
  const isLoggedIn = true;

  const renderMessage = () => {
    if (isLoggedIn) {
      return <h1>Welcome back!</h1>;
    } else {
      return <h1>Please log in.</h1>;
    }
  };

  return (
    <div>
      {renderMessage()}
    </div>
  );
};

export default ConditionalRenderingExample;
      

Here, we use a function renderMessage to handle the logic and then call it in the JSX.

5. Rendering Multiple Elements Based on Conditions

You can combine conditions to display different content. For example:


import React from 'react';

const ConditionalRenderingExample = () => {
  const isLoggedIn = false;
  const hasMessages = true;

  return (
    <div>
      {isLoggedIn ? (
        <div>
          <h1>Welcome back!</h1>
          {hasMessages && <p>You have new messages!</p>}
        </div>
      ) : (
        <h1>Please log in.</h1>
      )}
    </div>
  );
};

export default ConditionalRenderingExample;
      

Here, we check two conditions: if the user is logged in and if they have messages. The output depends on both conditions.

6. Conditional Rendering with null

Sometimes, you don’t want to show anything when a condition is false. In React, you can return null to render nothing.


import React from 'react';

const ConditionalRenderingExample = () => {
  const showWarning = false;

  return (
    <div>
      <h1>Dashboard</h1>
      {showWarning ? <p>Warning: Something went wrong!</p> : null}
    </div>
  );
};

export default ConditionalRenderingExample;
      

If showWarning is false, nothing will be displayed for that part of the component.

Why Conditional Rendering is Important

Conditional rendering lets you create dynamic, interactive UIs. You can show or hide parts of the UI, display error messages, or handle different states like loading or success.

Summary

Conditional rendering in React lets you control what users see based on specific conditions. You can use if statements, the ternary operator, the logical AND, or functions to manage what appears in your UI. These methods are essential for building dynamic and responsive user interfaces.