In most React applications, two concepts are used almost everywhere: list rendering and conditional rendering. Understanding these is crucial for building dynamic and efficient UIs. Today, we’ll break them down with clear examples and best practices.
List Rendering in React
List rendering is the process of displaying a collection of data-like products, user details, messages, or menu items — dynamically in your UI. In React, this is typically done using the map() function.
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
Why key is important
Each element in a rendered list needs a unique key. The key helps React:
- Distinguish between elements.
- Efficiently update or remove elements without re-rendering the entire list.
Pro tip: The key should be unique and stable. Good examples include id, employee number, or any value that doesn’t change over time. Avoid using the array index as a key unless your list is static and won’t change.
Using
map()is the React-friendly approach. Whileforloops can technically render lists, they’re often more complex and less readable.
Conditional Rendering in React
Conditional rendering allows you to show or hide elements based on certain conditions. This is especially useful for user interfaces that change dynamically.
Example: Showing login or signup pages based on the user's authentication state:
function AuthPage({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <Dashboard /> : <LoginSignup />}
</div>
);
}
You can apply conditions to:
- Individual elements.
- Entire pages or components.
Use cases include:
- Displaying a login/signup page only for users who are not logged in.
- Showing error messages or success notifications.
- Toggling UI features based on user roles or permissions.
Conditional rendering ensures your UI is dynamic, responsive, and user-focused.
Key Takeaways
-
List rendering uses
map()to transform arrays into JSX elements. - Always provide a unique
keyfor each list item to help React track changes efficiently. - Conditional rendering controls what is displayed based on conditions, making your UI adaptable.
- Combining both makes your React apps scalable and maintainable.
Once you grasp list and conditional rendering, you can turn raw data into interactive, real-world React applications.
Top comments (0)