SmartCodingTips

📊 Displaying Data in React

Once you've fetched data using fetch() or Axios, you'll usually want to display it in a component. This guide shows how to render that data conditionally and clearly.


📋 1. Mapping Over Data

Use map() to loop through arrays and render JSX elements dynamically.


const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
];

function UserList() {
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}
  

⚙️ 2. Conditional Rendering

You can show loading states, handle empty lists, or show errors using conditionals.


if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
if (data.length === 0) return <p>No items found.</p>;
  

✅ 3. Best Practices

  • Always provide a key when rendering lists
  • Keep fallback states like loading and error
  • Extract repeated UI into components