What is Conditional Rendering in React JS?

#conditional rendering

#React Js

Conditional rendering in React is a way to render different components or elements based on certain conditions. This allows you to build dynamic user interfaces that respond to changes in application state or props.

Methods of Conditional Rendering

  1. Using if Statements: You can use traditional `if` statements to conditionally render elements.
function Greeting(props) {
  if (props.isLoggedIn) {
    return <h1>Welcome back!</h1>;
  }
  return <h1>Please sign up.</h1>;
}

Using Ternary Operator: The ternary operator is a concise way to perform conditional rendering.

function Greeting(props) {
  return props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>;
}

Using Logical `&&` Operator: The logical `&&` operator can be used to include elements conditionally. If the condition is true, the element after `&&` will be rendered.

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 && <h2>You have {unreadMessages.length} unread messages.</h2>}
    </div>
  );
}

Using `switch` Statement: For multiple conditions, a `switch` statement can be a clear and organized approach.

function Greeting(props) {
  switch (props.status) {
    case 'loggedIn':
      return <h1>Welcome back!</h1>;
    case 'guest':
      return <h1>Please sign up.</h1>;
    default:
      return <h1>Hello, stranger!</h1>;
  }
}

Example: Conditional Rendering in a Component

Here’s a practical example of a component that conditionally renders content based on the user's login status:

import React, { useState } from 'react';

function UserGreeting() {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting() {
  return <h1>Please sign up.</h1>;
}

function Greeting(props) {
  if (props.isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

function LoginControl() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const handleLoginClick = () => setIsLoggedIn(true);
  const handleLogoutClick = () => setIsLoggedIn(false);

  let button;
  if (isLoggedIn) {
    button = <button onClick={handleLogoutClick}>Logout</button>;
  } else {
    button = <button onClick={handleLoginClick}>Login</button>;
  }

  return (
    <div>
      <Greeting isLoggedIn={isLoggedIn} />
      {button}
    </div>
  );
}

export default LoginControl;

In this example:

  • The Greeting component renders either UserGreeting or GuestGreeting based on the isLoggedIn prop.
  • The LoginControl component manages the isLoggedIn state and renders a login or logout button accordingly.

Best Practices

  1. Keep it Simple: Keep your conditional logic simple and readable. Break down complex conditions into smaller components if necessary.
  2. Component Composition: Use component composition to manage different rendering cases. This improves readability and maintainability.
  3. Avoid Nesting Ternaries: Avoid deeply nested ternary operators, as they can make your code hard to read. Instead, consider using if statements or breaking the logic into multiple components.

Conclusion

Conditional rendering is a powerful feature in React that allows you to build dynamic and responsive UIs. By understanding and utilizing the different methods of conditional rendering, you can create components that adapt to different states and user interactions efficiently.

Further, if you have any questions, please visit our website, Gurulabs Website Design Agency.