umami/components/common/Table.js

91 lines
2.3 KiB
JavaScript
Raw Normal View History

import React from 'react';
2021-02-16 14:05:20 +01:00
import PropTypes from 'prop-types';
2020-08-07 09:24:01 +02:00
import classNames from 'classnames';
import NoData from 'components/common/NoData';
import styles from './Table.module.css';
2021-02-16 14:05:20 +01:00
function Table({
2020-10-09 13:21:59 +02:00
columns,
rows,
empty,
className,
bodyClassName,
rowKey,
2020-10-10 02:58:27 +02:00
showHeader = true,
2020-10-09 13:21:59 +02:00
children,
}) {
if (empty && rows.length === 0) {
return empty;
}
return (
2020-10-09 11:56:15 +02:00
<div className={classNames(styles.table, className)}>
2020-10-10 02:58:27 +02:00
{showHeader && (
<div className={classNames(styles.header, 'row')}>
{columns.map(({ key, label, className, style, header }) => (
<div
key={key}
className={classNames(styles.head, className, header?.className)}
style={{ ...style, ...header?.style }}
>
{label}
</div>
))}
</div>
)}
2020-10-09 13:21:59 +02:00
<div className={classNames(styles.body, bodyClassName)}>
{rows.length === 0 && <NoData />}
2020-10-09 13:21:59 +02:00
{!children &&
rows.map((row, index) => {
const id = rowKey ? rowKey(row) : index;
return <TableRow key={id} columns={columns} row={row} />;
})}
{children}
2020-08-07 09:24:01 +02:00
</div>
</div>
);
}
2020-10-09 13:21:59 +02:00
2021-02-16 14:05:20 +01:00
const styledObject = PropTypes.shape({
className: PropTypes.string,
style: PropTypes.object,
});
Table.propTypes = {
columns: PropTypes.arrayOf(
PropTypes.shape({
cell: styledObject,
className: PropTypes.string,
header: styledObject,
key: PropTypes.string,
label: PropTypes.node,
render: PropTypes.func,
style: PropTypes.object,
}),
),
rows: PropTypes.arrayOf(PropTypes.object),
empty: PropTypes.node,
className: PropTypes.string,
bodyClassName: PropTypes.string,
rowKey: PropTypes.func,
showHeader: PropTypes.bool,
children: PropTypes.node,
};
export default Table;
2020-10-09 13:21:59 +02:00
export const TableRow = ({ columns, row }) => (
<div className={classNames(styles.row, 'row')}>
2022-03-02 04:28:44 +01:00
{columns.map(({ key, label, render, className, style, cell }, index) => (
2020-10-09 13:21:59 +02:00
<div
key={`${key}-${index}`}
className={classNames(styles.cell, className, cell?.className)}
style={{ ...style, ...cell?.style }}
>
2022-03-02 04:28:44 +01:00
{label && <label>{label}</label>}
2020-10-09 13:21:59 +02:00
{render ? render(row) : row[key]}
</div>
))}
</div>
);