Real applications rarely display the same UI all the time. A screen may show a loading message while data is being fetched, an error when a request fails, an empty state when there are no records, or a list when data is available. React uses normal JavaScript expressions and control flow patterns to handle these situations.
1 What is Conditional Rendering?
Conditional rendering means displaying different UI based on a condition. React does not provide a separate template language for basic conditions. JavaScript operators such as if, the ternary operator, and logical operators are commonly used.
2 if Statement
An ordinary if statement is useful when the component needs to decide what to return before the JSX is created.
function Status({ isLoggedIn }) {
if (!isLoggedIn) {
return <p>Please log in.</p>;
}
return <p>Welcome back.</p>;
}
This approach is especially readable when the conditions are complex or when different branches contain large pieces of UI.
3 Ternary Operator
The ternary operator is useful for choosing between two UI expressions.
function Status({ isLoggedIn }) {
return (
<p>
{isLoggedIn ? "Welcome back" : "Please log in"}
</p>
);
}
The general structure is condition ? valueWhenTrue : valueWhenFalse.
4 Logical AND
The logical AND operator can display something only when a condition is true.
function Notification({ count }) {
return (
<div>
{count > 0 && <p>You have notifications.</p>}
</div>
);
}
Be careful when the left side can be a number. For example, rendering {count && ...} when count is zero can result in an unexpected visible zero. A boolean expression such as count > 0 is clearer.
5 Multiple Conditions
For multiple states such as loading, error, empty, and success, explicit branching is usually easier to read than deeply nested ternary expressions.
function UserList({ loading, error, users }) {
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Unable to load users.</p>;
}
if (users.length === 0) {
return <p>No users found.</p>;
}
return <UserTable users={users} />;
}
6 Rendering Lists with map
The map function is commonly used to convert an array of data into an array of React elements.
const users = [
{ id: 1, name: "Anita" },
{ id: 2, name: "Rahul" }
];
function UserList() {
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
}
Each item should normally have a stable key so React can identify that item between renders.
7 Why Keys Are Important
A key gives React a stable identity for an element in a list. When items are added, removed, or reordered, keys help React determine which existing items correspond to which new items.
flowchart TD
A[Array of Data] --> B[map]
B --> C[React Element For Each Item]
C --> D[Stable Key]
D --> E[React Compares List Items]
E --> F[Required UI Updates]
8 Good Keys
A good key is stable and unique among the siblings in the list. A database identifier or another persistent item identifier is usually appropriate.
<li key={user.id}>{user.name}</li>
9 Why Array Index Can Be a Problem
Using the array index as a key can cause problems when list items are inserted, deleted, or reordered. The index can change even though the underlying item is the same.
// Usually avoid when the list can change
items.map((item, index) => (
<Row key={index} item={item} />
))
An index key can be acceptable for a truly static list where the order and membership never change, but a stable item identifier is generally preferable.
10 Filtering Before Rendering
Applications often filter data before mapping it into UI elements.
const activeUsers = users.filter(user => user.active);
return (
<ul>
{activeUsers.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
11 Combining Conditional Rendering and Lists
A common UI pattern is to show an empty message when no records exist and a list when records are available.
function ProductList({ products }) {
if (products.length === 0) {
return <p>No products available.</p>;
}
return (
<ul>
{products.map(product => (
<li key={product.id}>
{product.name}
</li>
))}
</ul>
);
}
12 Conditional Rendering Flow
flowchart TD
A[Component Renders] --> B{Data State}
B -->|Loading| C[Show Loading UI]
B -->|Error| D[Show Error UI]
B -->|Empty| E[Show Empty UI]
B -->|Data Available| F[Render List]
F --> G[Use Stable Keys]
13 Nested Lists
Nested arrays can also be rendered using map. Each mapped collection needs appropriate keys for the elements produced at that level.
categories.map(category => (
<section key={category.id}>
<h2>{category.name}</h2>
<ul>
{category.products.map(product => (
<li key={product.id}>
{product.name}
</li>
))}
</ul>
</section>
))
14 Common Mistakes
- Using deeply nested ternary operators that make the UI difficult to read.
- Forgetting keys when rendering arrays.
- Using unstable values such as random numbers as keys.
- Using array indexes as keys for lists that can be reordered or modified.
- Using
count &&without considering what happens when count is zero. - Mutating the original array instead of creating a new filtered or mapped result.
15 Important Concepts
| Concept | Purpose |
|---|---|
| if | Useful for clear branching before returning JSX. |
| Ternary | Chooses between two UI expressions. |
| Logical AND | Conditionally renders UI when a boolean condition is true. |
| map | Transforms an array of data into rendered elements. |
| filter | Creates a subset of data before rendering. |
| key | Provides stable identity for list elements. |
16 Interview Questions
- What is conditional rendering in React?
- When would you use
ifinstead of a ternary? - How does the ternary operator work in JSX?
- How can you conditionally render an element using
&&? - How do you render a list in React?
- Why does React require keys for lists?
- Why is using array index as a key sometimes problematic?
- What makes a good React key?
- Can you use
filterbeforemap? - How would you handle loading, error, empty, and success states?
17 Key Takeaways
- React uses normal JavaScript conditions for conditional rendering.
- Use clear branching for complex UI states.
- Use
mapto render collections. - Every dynamic list item should normally have a stable key.
- Stable keys help React correctly identify list items across renders.
- Use filtering and mapping to transform data into the required UI.
Conclusion
Conditional rendering and list rendering are used in almost every real React application. Understanding the difference between if, ternary expressions, logical conditions, map, filter, and stable keys gives you the foundation needed to build dynamic screens that correctly respond to changing data.