if/else Rendering Patterns in React JS – Complete Notes
Topic: Conditional Rendering using if/else statements, early returns, element variables, multiple conditions, and reusable rendering patterns in React JS.
Course Link: JustAcademy React JS Training
Demo Link: Register for React JS Course Demo
1. Introduction to if/else Rendering Patterns
In React JS, if/else rendering patterns are techniques used to display different user interface elements based on conditions. They use JavaScript control-flow statements to determine which JSX a component should return.
For example, an application may show a login form when a user is logged out and a dashboard when the user is logged in. Similarly, an online store may display an available message when a product is in stock and an unavailable message when it is out of stock.
React does not introduce a separate if/else syntax for JSX. Instead, developers use regular JavaScript conditions to decide what React should render.
Basic Example
function LoginStatus() {
const isLoggedIn = true;
if (isLoggedIn) {
return <h2>Welcome Back!</h2>;
} else {
return <h2>Please Log In</h2>;
}
}
export default LoginStatus;
Explanation: When isLoggedIn is true, the component displays “Welcome Back!”. When it is false, the component displays “Please Log In”.
2. Why Are if/else Rendering Patterns Important?
- Dynamic interfaces: Display different content based on application conditions.
- Authentication interfaces: Display login forms or account dashboards.
- Loading states: Show a loading message while data is being retrieved.
- Error handling: Display useful messages when something goes wrong.
- Form validation: Show validation messages when user input is invalid.
- Reusable components: Allow the same component to display different content through props.
- Readable code: Organize complex rendering logic into clear branches.
3. Basic if Statement Rendering Pattern
The if statement executes a block of JavaScript when its condition evaluates to true. In React, it can be used before the return statement to decide which JSX should be rendered.
Syntax
if (condition) {
return <div>Content for true</div>;
}
return <div>Default content</div>;
Example: Checking Product Availability
function ProductStatus() {
const isAvailable = true;
if (isAvailable) {
return <p>Product is available.</p>;
}
return <p>Product is currently unavailable.</p>;
}
export default ProductStatus;
How it works:
- The component creates an
isAvailable variable.
- The
if statement checks whether the product is available.
- If the condition is true, the component returns the availability message.
- If the condition is false, execution continues to the final return statement.
When to use it: Use a simple if statement when you need to handle one condition and provide a default output when that condition is not satisfied.
4. if/else Rendering Pattern
The if...else pattern allows a component to choose between two different outputs. It is useful when both possible conditions need their own content.
Syntax
if (condition) {
// Return JSX when the condition is true
} else {
// Return JSX when the condition is false
}
Example: Pass or Fail Result
function ExamResult() {
const marks = 35;
if (marks >= 40) {
return <h2>Congratulations! You Passed.</h2>;
} else {
return <h2>Sorry, You Failed.</h2>;
}
}
export default ExamResult;
Output: Sorry, You Failed.
The condition checks whether the marks are at least 40. Since the marks are 35, the else branch is executed.
Example: Online and Offline Status
function UserStatus() {
const isOnline = false;
if (isOnline) {
return <p>User is Online</p>;
} else {
return <p>User is Offline</p>;
}
}
This pattern is useful for status messages, login states, product availability, and simple application decisions.
5. Early Return Rendering Pattern
An early return is a pattern in which a component returns JSX as soon as a specific condition is met. It prevents the component from continuing through the remaining rendering logic.
Early returns are especially helpful for handling loading indicators, errors, missing data, and other conditions that should be handled before the main interface is displayed.
Example: Loading and Loaded States
function UserProfile() {
const isLoading = true;
if (isLoading) {
return <p>Loading user profile...</p>;
}
return (
<div>
<h2>User Profile</h2>
<p>Welcome to your profile.</p>
</div>
);
}
export default UserProfile;
Explanation: When isLoading is true, the component immediately returns the loading message. The profile interface is returned only when loading is false.
Example: Handling Multiple Early Returns
function Dashboard({ isLoading, hasError, user }) {
if (isLoading) {
return <p>Loading dashboard...</p>;
}
if (hasError) {
return <p>Unable to load dashboard.</p>;
}
if (!user) {
return <p>No user information found.</p>;
}
return (
<div>
<h2>Welcome, {user.name}!</h2>
<p>Your dashboard is ready.</p>
</div>
);
}
This example handles loading, error, and missing-user conditions before displaying the main dashboard.
6. Element Variable Rendering Pattern
Sometimes you may want to keep a single return statement while preparing different JSX elements in advance. In this situation, you can store the selected JSX in a variable and render that variable inside the main component.
Example
function AccountStatus() {
const isVerified = false;
let message;
if (isVerified) {
message = <p>Your account is verified.</p>;
} else {
message = <p>Please verify your account.</p>;
}
return (
<div>
<h2>Account Information</h2>
{message}
</div>
);
}
export default AccountStatus;
Explanation: The message variable stores one of the two JSX elements. The component then inserts the selected element into its main JSX using curly braces.
Advantages
- Keeps the main JSX structure consistent.
- Separates conditional logic from the returned markup.
- Can make more complicated rendering decisions easier to follow.
- Allows common page elements to remain outside the conditional branches.
7. if/else with Shared JSX Structure
When both branches use mostly the same JSX structure, you can keep the shared elements in one place and conditionally change only the content that differs.
Example: Task Completion
function TaskItem({ taskName, isCompleted }) {
let status;
if (isCompleted) {
status = "Completed";
} else {
status = "Pending";
}
return (
<div>
<h3>{taskName}</h3>
<p>Status: {status}</p>
</div>
);
}
export default TaskItem;
Explanation: Both outcomes display the same heading and paragraph structure. Only the value of the status variable changes, which avoids repeating the JSX.
8. Multiple Conditions Using if/else if/else
When there are more than two possible outcomes, the if...else if...else pattern allows you to check several conditions in sequence.
Syntax
if (conditionOne) {
// First outcome
} else if (conditionTwo) {
// Second outcome
} else if (conditionThree) {
// Third outcome
} else {
// Default outcome
}
Example: Grade Calculator
function GradeResult({ marks }) {
if (marks >= 90) {
return <h2>Grade A</h2>;
} else if (marks >= 75) {
return <h2>Grade B</h2>;
} else if (marks >= 60) {
return <h2>Grade C</h2>;
} else if (marks >= 40) {
return <h2>Grade D</h2>;
} else {
return <h2>Fail</h2>;
}
}
export default GradeResult;
Explanation: React displays the JSX returned by the first matching condition. The order of conditions matters because the first true branch is selected.
| Marks |
Result |
| 90–100 |
Grade A |
| 75–89 |
Grade B |
| 60–74 |
Grade C |
| 40–59 |
Grade D |
| Below 40 |
Fail |
Best practice: Put the most specific or highest-priority conditions in the appropriate order. If the inputs can fall outside the expected range, validate them before calculating the result.
9. Nested if/else Rendering Pattern
Nested if/else means placing one conditional statement inside another. This can be useful when a second decision depends on the result of the first decision. However, excessive nesting can make code difficult to read.
Example: User Access
function UserAccess({ isLoggedIn, isAdmin }) {
if (isLoggedIn) {
if (isAdmin) {
return <h2>Welcome, Administrator!</h2>;
} else {
return <h2>Welcome, User!</h2>;
}
} else {
return <h2>Please Log In</h2>;
}
}
export default UserAccess;
Explanation:
- If the user is not logged in, the login message appears.
- If the user is logged in and is an administrator, the administrator message appears.
- If the user is logged in but is not an administrator, the standard user message appears.
Alternative: Reduce Nesting
function UserAccess({ isLoggedIn, isAdmin }) {
if (!isLoggedIn) {
return <h2>Please Log In</h2>;
}
if (isAdmin) {
return <h2>Welcome, Administrator!</h2>;
}
return <h2>Welcome, User!</h2>;
}
The second version uses early returns to make the logic easier to read.
10. if/else Rendering with Props
Props allow parent components to pass information to child components. A child component can use the received props to choose which JSX should be rendered.
Example
function Greeting({ isLoggedIn, name }) {
if (isLoggedIn) {
return <h2>Welcome, {name}!</h2>;
} else {
return <h2>Please log in to continue.</h2>;
}
}
function App() {
return (
<div>
<Greeting isLoggedIn={true} name="Aarav" />
<Greeting isLoggedIn={false} name="Guest" />
</div>
);
}
export default App;
Explanation: The parent passes different prop values to the two Greeting instances. Each instance renders its own appropriate message.
11. if/else Rendering with State
React state is useful when a condition changes in response to user interaction. When state is updated using its setter function, React can re-render the component with the new state value.
Example: Show and Hide Details
import { useState } from "react";
function DetailsPanel() {
const [showDetails, setShowDetails] = useState(false);
if (showDetails) {
return (
<div>
<h2>Additional Details</h2>
<p>Here is the information you requested.</p>
<button onClick={() => setShowDetails(false)}>
Hide Details
</button>
</div>
);
} else {
return (
<div>
<h2>Details Panel</h2>
<button onClick={() => setShowDetails(true)}>
Show Details
</button>
</div>
);
}
}
export default DetailsPanel;
How it works:
- The state variable
showDetails starts as false.
- The component initially returns the button for showing details.
- Clicking the button updates the state to true.
- React renders the alternate branch containing the details.
- Clicking Hide Details updates the state to false and restores the original branch.
12. if/else Rendering for Loading, Error, and Success States
When working with APIs or other asynchronous data, applications often need different views for loading, error, empty, and successful states. These conditions can be handled clearly with early returns.
Example
function ProductList({ isLoading, error, products }) {
if (isLoading) {
return <p>Loading products...</p>;
}
if (error) {
return <p>Unable to load products. Please try again.</p>;
}
if (!products || products.length === 0) {
return <p>No products are available.</p>;
}
return (
<div>
<h2>Available Products</h2>
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
export default ProductList;
Explanation: The component checks each special state before rendering the product list. If the data is ready and contains products, it displays the list.
Important: This example assumes products is either an array or a falsy value. In a real application, ensure that API responses are validated and errors are represented consistently.
13. if/else Rendering with Authentication
Conditional rendering can switch between a login interface and a dashboard according to a login status.
Example
function AccountPage({ isLoggedIn, userName }) {
if (!isLoggedIn) {
return (
<div>
<h2>Login Required</h2>
<p>Please log in to view your account.</p>
<button>Login</button>
</div>
);
}
return (
<div>
<h2>Welcome, {userName}!</h2>
<p>You are viewing your account dashboard.</p>
<button>Logout</button>
</div>
);
}
export default AccountPage;
This component changes the visible interface according to the isLoggedIn prop. In a real application, the login and logout buttons must also be connected to the authentication workflow.
Security note: Conditional rendering controls the user interface only. The backend must independently verify permissions before returning protected data or performing protected actions.
14. if/else Rendering for Form Validation
Forms often need to display different messages depending on whether user input meets validation rules.
Example
function EmailStatus({ email }) {
if (!email) {
return <p>Please enter your email address.</p>;
} else if (!email.includes("@")) {
return <p>Please enter a valid email address.</p>;
} else {
return <p>Email format looks valid.</p>;
}
}
export default EmailStatus;
Explanation: The component checks whether the email is empty, whether it contains an at sign, and then displays an appropriate message. This is only a basic example; production email validation usually requires stronger validation rules.
15. if/else Rendering with a Switch Statement
When many distinct values produce different UI results, a switch statement can be clearer than a long chain of else if statements.
Example: Order Status
function OrderStatus({ status }) {
switch (status) {
case "pending":
return <p>Your order is pending.</p>;
case "processing":
return <p>Your order is being processed.</p>;
case "shipped":
return <p>Your order has been shipped.</p>;
case "delivered":
return <p>Your order has been delivered.</p>;
default:
return <p>Order status is unavailable.</p>;
}
}
export default OrderStatus;
Explanation: The component compares the status value with each case and returns the matching JSX. The default branch handles unexpected or unrecognized values.
16. if/else Rendering vs. Ternary Rendering
Both patterns allow you to choose between different UI outputs. The main difference is how the conditional logic is written and where it can be used.
| if/else Pattern |
Ternary Pattern |
| Uses JavaScript control-flow statements. |
Uses the conditional expression condition ? a : b. |
| Can contain multiple statements in each branch. |
Produces a value for the true or false branch. |
| Useful before the component's return statement. |
Can be used directly inside JSX curly braces. |
| Often easier to read for complex conditions. |
Often shorter for simple two-way choices. |
| Can use early returns to simplify rendering. |
Can become difficult to read when deeply nested. |
Equivalent Examples
Using if/else:
function LoginMessage({ isLoggedIn }) {
if (isLoggedIn) {
return <p>Welcome Back!</p>;
} else {
return <p>Please Log In</p>;
}
}
Using a ternary operator:
function LoginMessage({ isLoggedIn }) {
return (
<p>
{isLoggedIn ? "Welcome Back!" : "Please Log In"}
</p>
);
}
Choose the pattern that makes the code easiest to understand and maintain.
17. Common Mistakes in if/else Rendering
Mistake 1: Writing an if Statement Directly Inside JSX
Incorrect:
function Example() {
const isLoggedIn = true;
return (
<div>
{if (isLoggedIn) {
<p>Welcome</p>
}}
</div>
);
}
Why it fails: JSX curly braces accept JavaScript expressions, not a statement such as if.
Correct approach: Use an if/else statement before returning JSX, assign JSX to a variable, or use a ternary expression inside JSX.
Mistake 2: Writing Code After an Unconditional Return
function Example() {
return <p>Hello</p>;
// This statement can never execute.
// if (condition) { ... }
}
Place conditional logic before the relevant return statement. Once a function returns, its remaining statements are not executed.
Mistake 3: Using Separate Branches for Unchanged JSX
If both branches have the same markup and only one value changes, store the changing value in a variable instead of duplicating the entire JSX structure.
Mistake 4: Using Too Many Nested Conditions
Deep nesting can make a component difficult to understand. Prefer early returns, clear helper functions, or smaller components when the logic becomes complex.
Mistake 5: Forgetting a Default Branch
When using multiple conditions, consider what should happen if none of them match. A default return or else branch prevents unclear or unintended behavior.
Mistake 6: Expecting Normal Variables to Trigger Re-renders
Changing a regular variable does not automatically cause React to render the component again. Use state when a value must update the UI in response to user interaction.
18. Best Practices for if/else Rendering
- Use clear, meaningful condition names such as
isLoading, isLoggedIn, and hasError.
- Use early returns for loading, error, and missing-data states.
- Use
if/else if/else when several mutually exclusive conditions must be checked.
- Use element variables when the main JSX structure is shared between branches.
- Prefer simple conditions over deeply nested expressions.
- Handle unexpected values with a default branch.
- Use React state when user actions should update the visible interface.
- Keep business logic and complex validation separate from large JSX blocks when appropriate.
- Ensure sensitive actions are protected by backend authorization, not merely hidden in the UI.
- Test each branch so that both expected and fallback states behave correctly.
19. Practical Project: Student Result Dashboard
This mini project combines if/else, multiple conditions, and early returns to create a simple student result dashboard.
Complete Code
function StudentResult({ student }) {
if (!student) {
return <p>Student information is unavailable.</p>;
}
if (!student.isSubmitted) {
return <p>The result has not been submitted yet.</p>;
}
let grade;
if (student.marks >= 90) {
grade = "A";
} else if (student.marks >= 75) {
grade = "B";
} else if (student.marks >= 60) {
grade = "C";
} else if (student.marks >= 40) {
grade = "D";
} else {
grade = "Fail";
}
return (
<div>
<h2>Student Result Dashboard</h2>
<p>Name: {student.name}</p>
<p>Marks: {student.marks}</p>
<p>Grade: {grade}</p>
{student.marks >= 75 ? (
<p>Good work! Keep it up.</p>
) : (
<p>Keep practising to improve your result.</p>
)}
</div>
);
}
export default StudentResult;
Example Usage
function App() {
const student = {
name: "Rahul",
marks: 82,
isSubmitted: true
};
return <StudentResult student={student} />;
}
export default App;
Project Explanation
- The first early return handles missing student information.
- The second early return handles a result that has not been submitted.
- The if/else if/else chain calculates the grade based on marks.
- The ternary operator displays a message based on the student's marks.
- The component displays the dashboard only when the student information is available and the result has been submitted.
Practice Extensions
- Add a condition to reject marks below zero or above 100.
- Display “Distinction” for marks of 90 or higher.
- Add an error state when student data cannot be loaded.
- Use state to let the user switch between two sample students.
- Display a different message when the student has failed.
20. Interview Questions and Answers
Q1. What are if/else rendering patterns in React?
They are techniques that use JavaScript conditions to determine which JSX a component should return.
Q2. Can we use an if statement directly inside JSX?
No. An if statement is a JavaScript statement, while JSX curly braces in markup accept expressions. Use the if statement before the return, or use a ternary expression inside JSX.
Q3. What is an early return in React?
An early return exits a component function when a condition is satisfied, often to handle loading, errors, or missing data before rendering the main interface.
Q4. What is the purpose of an element variable?
An element variable stores JSX selected by conditional logic and allows that JSX to be inserted into the component's main return statement.
Q5. When should you use if/else if/else?
Use it when several conditions lead to different outcomes, such as assigning grades or displaying different order statuses.
Q6. How can conditional rendering depend on props?
A component can inspect props received from its parent and return JSX that matches their values.
Q7. How can conditional rendering depend on state?
A component can read a state variable and render the appropriate content. Updating the state with its setter function can trigger a re-render.
Q8. What is the difference between if/else and a ternary operator?
if/else is a statement suitable for more involved control flow. A ternary operator is an expression that selects one of two values and can be placed directly inside JSX.
Q9. How do you handle loading and error states?
Use early returns to display a loading message or error message before returning the main content.
Q10. Why should deeply nested conditions be avoided?
They can make code difficult to read, test, and maintain. Early returns and smaller components can make the rendering logic clearer.
21. Practice Exercises
- Create a component that displays a login message based on an
isLoggedIn prop.
- Use if/else to display “In Stock” or “Out of Stock”.
- Build a grade calculator using if/else if/else.
- Create a loading component that returns early when data is being fetched.
- Use an element variable to select between success and error messages.
- Create an order status component using a switch statement.
- Build a form validation message for an empty email field.
- Create a dashboard that shows different content based on a user's role.
22. Quick Revision Checklist
- Understand the purpose of conditional rendering.
- Know how to use if and if/else statements in a component.
- Understand early return rendering.
- Know how to store JSX in an element variable.
- Understand if/else if/else for multiple conditions.
- Know how props and state can control rendering.
- Understand when to use a switch statement.
- Avoid placing if statements directly inside JSX expressions.
- Keep conditional logic clear and avoid unnecessary nesting.
- Test each condition and its fallback output.
23. Conclusion
if/else rendering patterns are essential for building dynamic React JS applications. They allow developers to control which components, messages, or sections appear based on application conditions. Simple if/else statements, early returns, element variables, and multiple-condition branches each solve different rendering problems. Choosing the clearest pattern makes React applications easier to understand, test, and maintain.
Continue learning with JustAcademy React JS Training, or register for a React JS course demo.
Official Learning Resource: React Documentation – Conditional Rendering.