What is conditional rendering?
Conditional rendering is a technique used in programming, especially in frontend development, to selectively render components or elements based on certain conditions. Here's an explanation along with an example:
📌 Need for Conditional Rendering:
- Dynamic User Interfaces: Conditional rendering allows for creating dynamic user interfaces where components or elements are displayed or hidden based on specific conditions or user interactions.
- Flexible Content Display: It provides flexibility in displaying content based on different scenarios, such as user authentication status, data availability, or user preferences.
What is Conditional Rendering:
Conditional rendering involves using conditional statements (such as if-else or ternary operators) to determine whether to render a component or element in the UI. The condition evaluates to either true or false, and the component is rendered or not based on the result.
❓ How it Works:
In React, conditional rendering is commonly achieved using JavaScript expressions within JSX. Here's an example:
import React from 'react'; const ExampleComponent = ({ isLoggedIn }) => {
return (
<div>
<h1>Welcome</h1>
{isLoggedIn ? (
<p>You are logged in!</p>
) : (
<p>Please log in to continue.</p>
)}
</div>
);
};
export default ExampleComponent;`
In this example, the isLoggedIn
prop is used to conditionally render different messages based on whether the user is logged in. If isLoggedIn
is true, it renders "You are logged in!", otherwise, it renders "Please log in to continue."
Real-World Usage:
- Authentication: Conditional rendering is used to display different UI elements based on whether the user is authenticated or not. For example, showing a "Login" button if the user is not logged in, and a "Logout" button if they are logged in.
- Data Availability: It's used to render loading indicators or error messages while waiting for data to be fetched from an API. Once the data is available, it can render the fetched content.