jsx Copy code
import React, { useState, useEffect } from 'react';
// Simple inline spinner component with CSS animation
const Spinner = () => (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '200px',
fontSize: '18px',
}}
>
<div
style={{
border: '4px solid #f3f3f3',
borderTop: '4px solid #3498db',
borderRadius: '50%',
width: '40px',
height: '40px',
animation: 'spin 1s linear infinite',
}}
/>
<span style={{ marginLeft: '16px' }}>Loading...</span>
</div>
);
// Keyframes for spin animation (injected via style tag for standalone use)
const SpinStyles = () => (
<style jsx>{`
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`}</style>
);
const UserDataTable = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setUsers(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchUsers();
}, []);
if (loading) {
return (
<div style={{ padding: '20px' }}>
<SpinStyles />
<Spinner />
</div>
);
}
if (error) {
return (
<div
style={{
padding: '20px',
color: '#e74c3c',
textAlign: 'center',
fontSize: '18px',
}}
>
Error: {error}
</div>
);
}
return (
<div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
<SpinStyles />
<h2 style={{ marginBottom: '20px', color: '#2c3e50' }}>Users Data</h2>
<div
style={{
overflowX: 'auto',
boxShadow: '0 2px 10px rgba(0,0,0,0.1)',
borderRadius: '8px',
}}
>
<table
style={{
width: '100%',
borderCollapse: 'collapse',
backgroundColor: '#fff',
}}
>
<thead>
<tr
style={{
backgroundColor: '#3498db',
color: 'white',
}}
>
<th style={{ padding: '12px', textAlign: 'left' }}>ID</th>
<th style={{ padding: '12px', textAlign: 'left' }}>Name</th>
<th style={{ padding: '12px', textAlign: 'left' }}>Email</th>
<th style={{ padding: '12px', textAlign: 'left' }}>Phone</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr
key={user.id}
style={{
borderBottom: '1px solid #ecf0f1',
}}
>
<td style={{ padding: '12px' }}>{user.id}</td>
<td style={{ padding: '12px' }}>{user.name}</td>
<td style={{ padding: '12px' }}>{user.email}</td>
<td style={{ padding: '12px' }}>{user.phone}</td>
</tr>
))}
</tbody>
</table>
</div>
{users.length === 0 && (
<p style={{ textAlign: 'center', color: '#7f8c8d', marginTop: '20px' }}>
No data available.
</p>
)}
</div>
);
};
export default UserDataTable;