Comprehending Component Creation
I'm focused on creating a React functional component. My initial thought process involves fetching data from a public API, displaying it in a table, and handling loading states along with potential error scenarios. I'm prioritizing data fetching and display, considering the need for a user-friendly table representation.
Structuring the Component Logic
I'm presently building the component structure. I've pinpointed the necessary states: data, loading, and error. Using the useEffect hook to initiate the data fetch after the component mounts is the next step. I'm focusing on handling different scenarios like loading and errors with corresponding UI updates.
Outlining UI and Structure
I've transitioned to designing the UI. I plan to use a spinner or "Loading..." text for the loading state. If an error occurs, an error message will display. I'm focusing on structuring the table using <table>, <thead>, and <tbody> to render the fetched user data efficiently. The plan is to map the user array within the <tbody> tag.
Coding the React Component
I'm presently building the React component. I'm leveraging async/await within useEffect for better readability and incorporating a try/catch block for robust error handling. I'm also ensuring each table row has a unique key to satisfy React's requirement. Next up, it's about adding a style.
Formulating the Implementation Plan
I'm now detailing the steps for building the component. I've selected JSONPlaceholder as my API, due to its well-structured data. I'm focusing on defining the states (data, loading, error), crafting the useEffect hook to fetch data, and outlining the structure for loading, error, and table rendering UI. I am considering using a simple CSS spinner for better presentation.
Here is a complete, drop-in solution. It uses the JSONPlaceholder API (a free fake API for testing) to fetch a list of users.
I have included the Component logic, the JSX structure, and a simple CSS stylesheet to handle the styling and the spinner animation.
1. The React Component (UserTable.js)
import React, { useState, useEffect } from 'react';
import './UserTable.css'; // Assuming you save the CSS below
const UserTable = () => {
// 1. State Management
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// 2. Fetch Data Side Effect
useEffect(() => {
const fetchData = async () => {
try {
// Reset error and start loading
setError(null);
setLoading(true);
// Artificial delay to demonstrate the spinner (optional)
// await new Promise(r => setTimeout(r, 1000));
const response = await fetch('https://jsonplaceholder.typicode.com/users');
// Check if response is successful (status 200-299)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message || 'Something went wrong');
} finally {
// Always turn off loader, whether success or failure
setLoading(false);
}
};
fetchData();
}, []);
// 3. Conditional Rendering based on state
if (loading) {
return (
<div className="container center">
<div className="spinner"></div>
<p>Loading Data...</p>
</div>
);
}
if (error) {
return (
<div className="container center">
<div className="error-message">
<h3>Error Fetching Data</h3>
<p>{error}</p>
</div>
</div>
);
}
// 4. Render Table (Success State)
return (
<div className="container">
<h2>User Directory</h2>
<table className="data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>City</th>
<th>Company</th>
</tr>
</thead>
<tbody>
{data.map((user) => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.name}</td>
{/* Mailto link for better UX */}
<td>
<a href={`mailto:${user.email}`}>{user.email}</a>
</td>
<td>{user.address.city}</td>
<td>{user.company.name}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default UserTable;
2. The CSS (UserTable.css)
This CSS provides a clean table look and creates the spinning animation without needing external libraries like Bootstrap or Material UI.
/* Container layout */
.container {
max-width: 800px;
margin: 2rem auto;
padding: 0 1rem;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.center {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 200px;
}
/* Table Styling */
.data-table {
width: 100%;
border-collapse: collapse;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
background-color: #fff;
}
.data-table th,
.data-table td {
padding: 15px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.data-table th {
background-color: #009879;
color: #ffffff;
text-transform: uppercase;
font-size: 0.85rem;
letter-spacing: 0.05rem;
}
.data-table tr:hover {
background-color: #f5f5f5;
}
/* Error State */
.error-message {
color: #d8000c;
background-color: #ffbaba;
border: 1px solid #d8000c;
padding: 20px;
border-radius: 5px;
text-align: center;
}
/* Loading Spinner */
.spinner {
border: 4px solid rgba(0, 0, 0, 0.1);
width: 36px;
height: 36px;
border-radius: 50%;
border-left-color: #009879;
animation: spin 1s linear infinite;
margin-bottom: 10px;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
Key Features of this implementation:
- Try/Catch/Finally: It wraps the fetch logic in a
try/catch block. The finally block ensures that the loading spinner stops spinning whether the request succeeds or fails.
- Error Handling: It checks
if (!response.ok) because the native fetch API does not throw an error automatically for 404 or 500 server errors; it only throws on network failure.
- Clean Separation: It renders specific logic (Loading, Error, Success) using early returns, making the code easier to read than using ternary operators inside the JSX.
- Data Mapping: It iterates over the array using
.map(), ensuring a unique key prop (user.id) is assigned to every table row to prevent React reconciliation warnings.