Conditional Rendering in ReactJS is the technique of showing or hiding parts of the UI based on certain conditions β like whether a user is logged in, a form has been submitted, or data is loading. Itβs similar to how we use if, else, or ternary operators in JavaScript, but within JSX syntax. This makes React applications flexible and user-friendly.
In React, you can conditionally render elements using:
- If/else statements
- Ternary operators π
- Logical AND (&&) operator
This concept is extremely helpful when you want to toggle components, display alerts, hide or show elements, or even redirect users based on state or props.
In this article, weβll build a simple component that checks whether a user is logged in. Depending on the state, the component will show either a “Welcome Back!” message or a prompt to log in.
β Example: Login Toggle using Conditional Rendering
π§© React Functional Component (HTML + JavaScript)
import React, { useState } FROM 'react';
FUNCTION ConditionalRenderApp() {
const [isLoggedIn, setIsLoggedIn] = useState(FALSE);
const toggleLogin = () => {
setIsLoggedIn(!isLoggedIn);
};RETURN (
<div STYLE={{ padding: '20px', fontFamily: 'Arial' }}>
<h2>π Conditional Rendering Example</h2>
{/* Conditional Message */}
{isLoggedIn ? (
<p>Welcome back, <strong>Vijay Kumar</strong>! π</p>
) : (
<p>Please login TO continue.</p>
)}
{/* Toggle Button */}
<button onClick={toggleLogin} STYLE={{ padding: '10px 20px', marginTop: '10px' }}>
{isLoggedIn ? 'Logout' : 'Login'}
</button>
</div>
);}export DEFAULT ConditionalRenderApp;
π‘ Key Points:
- Ternary operator is used here for clean JSX rendering.
- You can also use && for short conditional logic like {isLoggedIn && Logged In!}
- The button toggles login state using useState.
What is the purpose of conditional rendering in React?
In React, conditional rendering is the process of displaying different content based on certain conditions or states. It allows you to create dynamic user interfaces that can adapt to changes in data and user interactions. In this process, you can use conditional statements to decide what content should be rendered.
What is the difference between conditional rendering and dynamic rendering?
Dynamic rendering involves changing the content based on variables, while conditional rendering controls whether elements appear or not. Using these tools effectively can help you create flexible, responsive, and interactive user interfaces.
What is rendering in React?
Rendering is the process of React asking your components to describe what they want the UI to look like, based on their current props and state. And then taking that and applying any necessary updates to the DOM.
Related Topics | You May Also Like
|
π Get Free Course β
π Salesforce Administrators π Salesforce Lightning Flow Builder π Salesforce Record Trigger Flow Builder |
π Get Free Course β |
