SmartCodingTips

🧾 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.