Apologies for the ambiguous question title, it was difficult to come up with something more specific.
I am currently exploring the Typescript implementation of Material-UI tables, specifically focusing on the table section titled "Sorting and selecting". There is a helpful Sandbox demo available for reference.
As I work on multiple pages with tables, I noticed that by directly copying and pasting the code (with necessary data and style modifications), there is a significant amount of duplicated code. While I have been able to address most of these duplications, I am facing challenges with the EnhancedTableProps
and EnhancedTableHead
.
The issue lies in the fact that they rely on the Data
interface, which differs for each table. This necessitates keeping the Data specific to each table and prevents unification.
I am struggling to find an appropriate solution mainly due to my limited experience with Typescript.
interface EnhancedTableProps {
classes: ReturnType<typeof useStyles>;
numSelected: number;
onRequestSort: (event: React.MouseEvent<unknown>, property: keyof Data) => void;
onSelectAllClick: (event: React.ChangeEvent<HTMLInputElement>) => void;
order: Order;
orderBy: string;
rowCount: number;
}
function EnhancedTableHead(props: EnhancedTableProps) {
const { classes, onSelectAllClick, order, orderBy, numSelected, rowCount, onRequestSort } = props;
const createSortHandler = (property: keyof Data) => (event: React.MouseEvent<unknown>) => {
onRequestSort(event, property);
};
return (
<TableHead>
<TableRow>
<TableCell padding="checkbox">
<Checkbox
indeterminate={numSelected > 0 && numSelected < rowCount}
checked={rowCount > 0 && numSelected === rowCount}
onChange={onSelectAllClick}
inputProps={{ 'aria-label': 'select all desserts' }}
/>
</TableCell>
{headCells.map((headCell) => (
<TableCell
key={headCell.id}
align={headCell.numeric ? 'right' : 'left'}
padding={headCell.disablePadding ? 'none' : 'normal'}
sortDirection={orderBy === headCell.id ? order : false}
>
<TableSortLabel
active={orderBy === headCell.id}
direction={orderBy === headCell.id ? order : 'asc'}
onClick={createSortHandler(headCell.id)}
>
{headCell.label}
{orderBy === headCell.id ? (
<span className={classes.visuallyHidden}>
{order === 'desc' ? 'sorted descending' : 'sorted ascending'}
</span>
) : null}
</TableSortLabel>
</TableCell>
))}
</TableRow>
</TableHead>
);
}