⚛️Mastering Conditional Rendering in React: Best Practices & Code Examples🚀
🎯Understanding Conditional Rendering in React
Conditional rendering in React allows you to control what gets displayed on the screen based on certain conditions.
For example, if a user is logged in, you might display a personalized dashboard. If not, you could show a login form instead. React provides multiple ways to handle conditional rendering, such as:
🎯Best Practices for Conditional Rendering
Conditional rendering is a powerful feature in React, but writing clean and maintainable code is just as important. Here are some best practices to follow
🔥Ways to implement conditional rendering in React
1. Using an If-Else statements
Best for handling complex conditions.
import React from "react";
const ListGroupNew = () => {
const items: string[] = ["Colombo", "Kandy", "Badulla", "Matara", "Galle"];
let message;
if (items.length === 0) {
message = <p>Items are not found</p>;
} else {
message = <p>Items are found</p>;
}
return (
<>
<ul className="list-group">
{items.map((item, index) => (
<li key={index} className="list-group-item">
{item}
</li>
))}
{message}
</ul>
</>
);
};
export default ListGroupNew;
👉 Straightforward but can make components lengthy when handling multiple conditions.
2. Using Ternary Operators (condition ? true: false)
A cleaner way to render based on a simple condition.
import React from "react";
const ListGroupNew = () => {
const items: string[] = ["Colombo", "Kandy", "Badulla", "Matara", "Galle"];
return (
<>
<ul className="list-group">
{items.length === 0 ? (
<p>Items are not found.</p>
) : (
<p>Items are found</p>
)}
</ul>
</>
);
};
export default ListGroupNew;
✅Best for simple conditions with two outcomes.
3. Using Logical AND (&&) Operator
Efficient when rendering a single element conditionally.
import React from "react";
const ListGroupNew = () => {
const items: string[] = [];
return <>{items.length === 0 && <p>Items are not found</p>}</>;
};
export default ListGroupNew;
🚀Best when rendering a single element conditionally.
4. Switch Case Statements
Best for handling multiple conditions in an organized way.
import React from "react";
const ListGroupNew = () => {
const items: string[] = ["Colombo", "Kandy", "Badulla", "Matara", "Galle"];
switch (items.length) {
case 0:
return <p>No items available.</p>;
default:
return <p>{items.length} items available.</p>;
}
};
export default ListGroupNew;
✅Avoid deeply nested if-else conditions and improve readability.
Very helpful 💓