DEV Community

Cover image for Conditional Rendering in React && Build Dynamic User Interfaces
Joshua Medina
Joshua Medina

Posted on

Conditional Rendering in React && Build Dynamic User Interfaces

Conditional rendering plays a crucial role in building modern and interactive user interfaces in React. With the ability to selectively render components and content based on specific conditions, you can create dynamic UIs that adapt and respond to user interactions. In this blog post, we will explore various techniques and best practices to utilizing conditional rendering in React and unlock its full potential.

1. Conditional Rendering Basics

In React, conditional rendering can be achieved using JavaScript expressions within JSX. Let's start with a simple example using if/else:

function Greeting({ isLoggedIn }) {
  if(isLoggedIn){
    return <h1>Welcome back!</h1>;
  }else {
    return <h1>Please log in or sign up.</h1>;
  }
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the 'Greeting' component conditionally renders a different greeting to the users based on whether the prop 'isLoggedIn' is true or false.

2. Ternary Operator for Concise Rendering

As with vanilla JavaScript, we can utilize a ternary operator to handle some of our conditional rendering in React, while being a bit more concise.

function Greeting({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up or log in.</h1>}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Using the ternary operator eliminates the if/else statements and makes the code more succinct and readable.

3. Logical && Operator for Conditional Rendering

Another approach to conditional rendering is using the logical && operator. The && allows you to conditionally render

...its(&&) right side if the left side (condition) is true, or render nothing otherwise. -React.dev

function Banner(){

const [isCartHovered, setIsCartHovered] = useState(false);

const toggleCart = () => {
  setIsCartHovered(!isCartHovered);
};

return (
  <div>
    <button className="cartButton" 
      onMouseEnter={toggleCart}
      onMouseLeave={toggleCart}
    >
    Shopping Cart
    </button>
    {isCartHovered && <HoverCart />}
  </div>
)
}
Enter fullscreen mode Exit fullscreen mode

The above example of the && operator was taken directly from my E-Commerce-Store application. The code allows users to preview the items in their cart by conditionally rendering the <HoverCart /> component only when isCartHovered is true. The isCartHovered is only true when the user hovers over the cart button.

4. Switch Statements for Complex Conditions

In certain scenarios where you have multiple conditions and need to render different components based on specific cases, using switch statements can provide a more organized approach. Let's take a look at an example:

function UserProfile({ userRole }) {
  switch (userRole) {
    case 'admin':
      return <AdminProfile />;
    case 'manager':
      return <ManagerProfile />;
    case 'employee':
      return <EmployeeProfile />;
    default:
      return <GuestProfile />;
  }
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the UserProfile component renders different profiles based on the userRole prop. By using switch statements, it becomes easier to handle various cases and maintain readable code.

Switch statements are particularly useful when you have multiple conditions with different possible outcomes. They provide a clean and structured way to handle complex conditional rendering in your React components.

Conclusion

Conditional rendering is a powerful feature in React that enables the creation of dynamic and responsive user interfaces. By mastering techniques such as JavaScript expressions, the ternary operator, logical && operator, and switch statements, developers can build UIs that adapt and respond to specific conditions. Whether it's simple rendering, concise logic, handling conditional elements, or managing complex scenarios, understanding and applying these conditional rendering techniques will empower React developers to create engaging and interactive user interfaces with ease."

Top comments (0)