π§Ύ Conditional Lists & Empty States in React
Sometimes, the data you're rendering may be empty or need conditional rendering logic. React makes it easy to handle such situations cleanly.
π Showing a List Only When Items Exist
Use a conditional check to render the list only when thereβs data.
function TodoList({ todos }) {
return (
<div>
{todos.length > 0 && (
<ul>
{todos.map((todo) => (
<li key={todo.id}>β
{todo.text}</li>
))}
</ul>
)}
</div>
);
}
π« Handling Empty States Gracefully
When no data is present, show a message or fallback UI.
function TodoList({ todos }) {
if (todos.length === 0) {
return <p>No tasks found. You're all caught up! π</p>;
}
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
β Using Ternary Operator
You can also write a concise version using a ternary expression:
function TodoList({ todos }) {
return (
<div>
{todos.length === 0
? <p>No items to display</p>
: <ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
}
</div>
);
}
β Best Practices
- Always check array length before mapping.
- Show a friendly empty message to improve UX.
- Extract logic into smaller components when lists become complex.
π Summary
- Render lists only when they contain items.
- Handle empty states with conditional logic.
- Use concise syntax like
&&
or ternaries for small checks.