React Conditional Rendering

Conditional rendering in React allows you to render different content or components based on certain conditions or state values. It helps you dynamically control what gets displayed in your UI based on specific conditions. 

Three different ways to implement conditional rendering: 

  1. Conditional Rendering using If and Else statement 
  2. Conditional Rendering using Ternary Operator 
  3. Conditional Rendering using && Operator (Short Circuit Operator)

1. Conditional Rendering using If and Else statement

In functional components, you can achieve conditional rendering using if and else statements inside the body of the component. However, since functional components don't have a render() method like class components, you need to use regular JavaScript control flow instead.

Here's an example:
import React, { useState } from 'react';

const MyComponent = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  if (isLoggedIn) {
    return <p>Welcome, user!</p>;
  } else {
    return <p>Please log in to continue.</p>;
  }
};

export default MyComponent;
In this example, the MyComponent functional component uses the useState hook to declare a state variable named isLoggedIn and its corresponding setter function setIsLoggedIn, initialized to false.

Inside the component's body, an if statement is used to conditionally render different JSX based on the value of isLoggedIn. If isLoggedIn is true, the component returns the JSX element <p> Welcome, user!</p>. If isLoggedIn is false, the component returns the JSX element <p>Please log in to continue.</p>.

2. Conditional Rendering using Ternary Operator

You can use a ternary operator (condition ? expression1 : expression2) to perform inline conditional rendering. Here's an example:
import React from 'react';

function MyComponent() {
  const isLoggedIn = true;

  return isLoggedIn ? <p>Welcome, user!</p> : <p>Please log in to continue.</p>;
}

export default MyComponent;
This approach allows you to render different JSX expressions based on the condition. If the condition is true, it evaluates expression1; otherwise, it evaluates expression2.

3. Conditional Rendering using && Operator (Short Circuit Operator)

You can use the logical && operator to conditionally render a JSX element. Here's an example:
import React from 'react';

function MyComponent() {
  const isLoggedIn = true;

  return isLoggedIn && <p>Welcome, user!</p>;
}

export default MyComponent;
In this example, if isLoggedIn is true, the second part of the expression (<p>Welcome, user!</p>) is evaluated and rendered. If isLoggedIn is false, the entire expression short-circuits, and nothing is rendered.

Comments