Skip to content

Instantly share code, notes, and snippets.

@malerba118
Created April 6, 2023 15:55
Show Gist options
  • Save malerba118/ce26d85ecb1d37923ee39fad5096383d to your computer and use it in GitHub Desktop.
Save malerba118/ce26d85ecb1d37923ee39fad5096383d to your computer and use it in GitHub Desktop.
Table Component
import { Box, Center, Flex, Grid, Stack, Text } from "@chakra-ui/react";
import React, { ReactNode } from "react";
export interface TableProps<T extends { id: string }> {
children: ReactNode;
data: T[];
emptyLabel?: string;
}
export interface ColumnDefinition {
id: string;
label?: string;
fr?: number;
align?: "start" | "center" | "end";
children: (row: any) => ReactNode;
}
const TableColumn = (props: ColumnDefinition) => null;
export default function Table<T extends { id: string }>({
children,
data,
emptyLabel,
}: TableProps<T>) {
const columns: ColumnDefinition[] = React.Children.toArray(children)
.filter((child: any) => child?.type === TableColumn)
.map((child: any) => child.props);
const templateColumns = columns.map((c) => c.fr + "fr").join(" ");
return (
<Box>
<Grid
px={3}
gap={2}
mb={2}
color="whiteAlpha.500"
templateColumns={templateColumns}
>
{columns.map((col) => (
<Flex
key={col.id}
pos="relative"
justifyContent={col.align || "start"}
textAlign={col.align || "start"}
minWidth={0}
>
<Text w="fit-content">{col.label}</Text>
</Flex>
))}
</Grid>
<Stack>
{data.length === 0 && !!emptyLabel && (
<Center
px={3}
gap={2}
bg="whiteAlpha.50"
border="sm"
h={10}
alignItems="center"
rounded="xl"
color="whiteAlpha.700"
>
<Text>{emptyLabel}</Text>
</Center>
)}
{data.map((row) => (
<Grid
key={row.id}
px={3}
gap={2}
bg="whiteAlpha.50"
border="sm"
h={10}
alignItems="center"
rounded="xl"
color="whiteAlpha.700"
templateColumns={templateColumns}
>
{columns.map((col) => (
<Flex
key={col.id}
pos="relative"
justifyContent={col.align || "start"}
textAlign={col.align || "start"}
minWidth={0}
>
{col.children(row)}
</Flex>
))}
</Grid>
))}
</Stack>
</Box>
);
}
Table.Column = TableColumn;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment