Rendering & Lists
Learn how to show conditional UI and render arrays with lists in React.
Conditional Rendering and Lists in React
When building a React application, you often need to display different content based on certain conditions. For example, you may want to show a Login button if the user is not signed in or display a Logout button if they are already logged in.
Similarly, websites often display multiple items such as products, students, blog posts, or comments. Instead of writing the same code repeatedly, React allows you to create these items from an array using lists.
Conditional rendering and lists are two important React concepts that help you create dynamic and interactive user interfaces.
What is Conditional Rendering?
Conditional rendering means displaying different content depending on a condition. In simple words, React decides what should appear on the screen based on a value or expression.
Real-World Example
Imagine a movie theater.
- If you have a valid ticket, you can enter.
- If you do not have a ticket, you cannot enter.
The displayed result depends on a condition. React works in the same way by checking a condition before displaying content.
Why Use Conditional Rendering?
Conditional rendering helps you:
- Show or hide elements.
- Display different messages.
- Handle login and logout screens.
- Show loading indicators.
- Display error messages.
- Show content only when data is available.
It makes your application smarter and more user-friendly.
Using the if Statement
One way to perform conditional rendering is by using an if statement.
function Greeting() {
const isLoggedIn = true;
if (isLoggedIn) {
return <h2>Welcome Back!</h2>;
}
return <h2>Please Log In</h2>;
}Output
Welcome Back!If isLoggedIn becomes false, React displays:
Please Log InUsing the Ternary Operator
The ternary operator is a shorter way to write simple conditions.
function Greeting() {
const isLoggedIn = false;
return (
<h2>
{isLoggedIn ? "Welcome Back!" : "Please Log In"}
</h2>
);
}Explanation
The syntax is:
condition ? trueValue : falseValueThis approach is commonly used in React because it is clean and easy to read.
Using the Logical AND (&&) Operator
Sometimes you only want to display something when a condition is true.
function App() {
const isAdmin = true;
return (
<div>
{isAdmin && <button>Delete User</button>}
</div>
);
}If isAdmin is true, the button appears. If it is false, React displays nothing.
What are Lists in React?
A list is a collection of similar items.
Examples include:
- Product lists
- Student names
- Blog posts
- Comments
- Menu items
- Notifications
Instead of writing each item manually, React can create them automatically from an array.
Rendering a List with map()
React commonly uses JavaScript's map() method to display lists.
function App() {
const fruits = ["Apple", "Banana", "Orange"];
return (
<ul>
{fruits.map((fruit) => (
<li>{fruit}</li>
))}
</ul>
);
}Output
• Apple
• Banana
• OrangeThe map() method loops through every item in the array and creates a list item for each one.
Rendering Objects in a List
Lists often contain objects instead of simple text.
function App() {
const products = [
{ id: 1, name: "Laptop", price: 50000 },
{ id: 2, name: "Mouse", price: 999 },
{ id: 3, name: "Keyboard", price: 1499 }
];
return (
<div>
{products.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>₹{product.price}</p>
</div>
))}
</div>
);
}Output
Laptop
₹50000
Mouse
₹999
Keyboard
₹1499This approach is commonly used in e-commerce websites.
Why is the key Prop Important?
When displaying lists, React requires a key for each item.
<div key={product.id}>The key helps React identify each item efficiently when the list changes. Using a unique value such as an ID improves performance and prevents unexpected rendering issues.
Avoid using the array index as a key unless there is no better unique value available.
Combining Conditional Rendering and Lists
These two concepts are often used together.
function App() {
const products = ["Laptop", "Mouse", "Keyboard"];
return (
<div>
{products.length > 0 ? (
<ul>
{products.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
) : (
<p>No products available.</p>
)}
</div>
);
}How It Works
- If products exist, React displays the list.
- If the array is empty, React displays a message instead.
This creates a better experience for users.
Real-World Example
Imagine you are building an online shopping website.
- If a customer is logged in, show My Orders.
- If not, show Login.
- Store all products in an array.
- Use map() to display each product card.
- If no products are available, display "No products found."
This approach keeps your code clean and avoids unnecessary repetition.
Best Practices
When using conditional rendering and lists:
- Use the ternary operator for simple conditions.
- Use if statements for more complex logic.
- Use && when displaying content only if a condition is true.
- Use map() to render lists instead of writing repeated code.
- Always provide a unique key for list items.
- Keep your conditions simple and readable.
Following these practices makes your React applications easier to understand and maintain.
Summary
Conditional rendering and lists are essential concepts in React for building dynamic user interfaces. Conditional rendering allows you to display different content based on specific conditions, while lists help you generate multiple UI elements from an array of data.
Together, they reduce repetitive code, improve readability, and make applications more interactive. Whether you are showing login screens, displaying products, or handling empty data, these concepts will be used in almost every React project.
Key Takeaways
- Conditional rendering displays different content based on a condition.
- Common techniques include if statements, the ternary operator, and the && operator.
- Lists allow you to display multiple items from an array.
- Use JavaScript's map() method to render lists efficiently.
- Always provide a unique key prop when rendering list items.
- Conditional rendering and lists are often used together in real-world applications.
- These concepts help reduce duplicate code and create dynamic, user-friendly interfaces.
- Mastering conditional rendering and lists is an important step toward building professional React applications.