Skip to main content

data-table

Please give me a short React Typescript (functional components, can use hooks): Data Table: Construct a table that displays a list of items with simple sorting and filtering capabilities.

Certainly! Below you'll find a simple implementation of a data table in React with TypeScript, using functional components and hooks. This table will allow you to sort and filter the list of items it displays. For brevity, this example uses basic inline styles and simplifies some concepts:

import React, { useState, useMemo } from 'react';

type Item = {
id: number;
name: string;
quantity: number;
price: number;
};

type SortOrder = 'asc' | 'desc';

const initialItems: Item[] = [
{ id: 1, name: 'Apple', quantity: 3, price: 1.2 },
{ id: 2, name: 'Orange', quantity: 7, price: 0.5 },
// ... other items
];

const DataTable: React.FC = () => {
const [items, setItems] = useState(initialItems);
const [filter, setFilter] = useState('');
const [sortKey, setSortKey] = useState<keyof Item | null>(null);
const [sortOrder, setSortOrder] = useState<SortOrder>('asc');

const sortedItems = useMemo(() => {
if (!sortKey) return items;

return [...items].sort((a, b) => {
if (a[sortKey] < b[sortKey]) return sortOrder === 'asc' ? -1 : 1;
if (a[sortKey] > b[sortKey]) return sortOrder === 'asc' ? 1 : -1;
return 0;
});
}, [items, sortKey, sortOrder]);

const filteredAndSortedItems = useMemo(() => {
const lowercasedFilter = filter.toLowerCase();
return sortedItems.filter((item) =>
item.name.toLowerCase().includes(lowercasedFilter)
);
}, [filter, sortedItems]);

const handleSort = (key: keyof Item) => {
setSortKey(key);
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
};

return (
<div>
<input
type="text"
placeholder="Filter by name..."
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
<table>
<thead>
<tr>
<th onClick={() => handleSort('name')}>Name</th>
<th onClick={() => handleSort('quantity')}>Quantity</th>
<th onClick={() => handleSort('price')}>Price</th>
</tr>
</thead>
<tbody>
{filteredAndSortedItems.map((item) => (
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.quantity}</td>
<td>${item.price.toFixed(2)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

export default DataTable;

This component DataTable defines an Item type with id, name, quantity, and price. It uses the useState hook to manage the state for items, filter text, sorting key, and sorting order. The useMemo hook is used to compute sorted and filtered items based on the current state to optimize performance, avoiding unnecessary computations on each render.

The handleSort function toggles the sorting order and sets the key for sorting. Clicking the table headers will sort the table by that column.

Remember to install the necessary types for React if you haven't already:

npm install @types/react

This code is simplified and meant to serve as a starting point. For a real-world application, you'd likely need to add more robust styling, accessibility features, and possibly pagination.