Accessible tables support screen readers and keyboard navigation.
Code:
1function AccessibleTable({ data }) {2 return (3 <table aria-label="User data">4 <caption>User Information</caption>5 <thead>6 <tr>7 <th scope="col">Name</th>8 <th scope="col">Email</th>9 <th scope="col">Role</th>10 </tr>11 </thead>12 <tbody>13 {data.map(row => (14 <tr key={row.id}>15 <td>{row.name}</td>16 <td>{row.email}</td>17 <td>{row.role}</td>18 </tr>19 ))}20 </tbody>21 </table>22 );23}
Sortable table:
1function SortableTable({ data }) {2 const [sortConfig, setSortConfig] = useState({ key: null, direction: "asc" });34 const handleSort = (key) => {5 setSortConfig(prev => ({6 key,7 direction: prev.key === key && prev.direction === "asc" ? "desc" : "asc",8 }));9 };1011 return (12 <table>13 <thead>14 <tr>15 <th>16 <button17 onClick={() => handleSort("name")}18 aria-sort={sortConfig.key === "name" ? sortConfig.direction + "ending" : "none"}19 >20 Name21 </button>22 </th>23 <th>Email</th>24 </tr>25 </thead>26 <tbody>27 {/* rows */}28 </tbody>29 </table>30 );31}
ARIA attributes:
aria-label — table descriptioncaption — visible descriptionscope — column/row header scopearia-sort — sort directionaria-selected — selected row