React conditional

Understanding react-conditional in React

React allows developers to control what gets displayed in the UI dynamically. This process is known as conditional rendering, where elements or components are displayed based on specific conditions.


Syntax of Conditional Rendering

There are multiple ways to handle conditional rendering in React:


1. Using if-else Statement

The simplest way to decide which component or element should be rendered.

Example:

function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>Welcome Back!</h1>;
  } else {
    return <h1>Please Sign In</h1>;
  }
}

2. Using Ternary Operator (? :)

A compact way to render elements based on conditions.

Example:

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

3. Using Logical && Operator

If a condition is true, React renders the next element; otherwise, nothing appears.

Example:

function Backpack(props) {
  const items = props.items;
  return (
    <>
    <h1>Backpack</h1>
      {items.length > 0 && (
        <h2>You have {items.length} items in your backpack.</h2>
      )}
    
  );
}

const items = ['Notebook', 'Pen', 'Laptop'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render();

4. Using switch Statement

Useful when multiple conditions exist.

Example:

function UserRole({ role }) {
  switch (role) {
    case "admin":
      return <h2>Admin Panel </h2>;
    case "editor":
      return <h2>Editor Dashboard </h2>;
    default:
      return <h2>Visitor View </h2>;
  }
}

5. Using HOC (Higher-Order Components) for Conditional Wrapping

A more advanced way to control visibility.

Example:

function withAuthentication(Component) {
  return function AuthenticatedComponent({ isAuthenticated, ...props }) {
    return isAuthenticated ?  : <p>Access Denied</p>;
  };
}

const SecureContent = withAuthentication(() => <h1>Secure Data</h1>);

6. Using Conditional Rendering inside JSX

React allows embedding JavaScript expressions inside JSX.

Example:

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

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render();

Practical Example: Show or Hide a Button

A real-world implementation where a button is conditionally displayed.

Example:

import { useState } from "react";

function ShowHideButton() {
  const [visible, setVisible] = useState(true);

  return (
    <div>
      {visible && <button> Click Me</button>}
      <button onClick={() => setVisible(!visible)}>Toggle Button</button>
    </div>
  );
}

Conclusion

Mastering conditional rendering in React enables flexible UI updates based on user interaction, state changes, or external conditions. Using the appropriate approach depends on complexity, readability, and performance considerations.

Previous Next