summaryrefslogtreecommitdiff
path: root/src/components/ListTable.tsx
blob: 79e1ecd5fc311f407002cbc4b03327bd21e65d3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import React from 'react';
import _ from 'lodash';

export interface Field {
  key: string;
  label: string;
  transform?: (value: string) => JSX.Element | string;
}

interface Props {
  items?: any[];
  fields: Field[];
  handleRowClick?: (index: number) => void;
}

const getItemField = (item: any, field: Field) => {
  const value = _.get(item, field.key);
  return field.transform ? field.transform(value) : value;
};


const ListTable: React.FC<Props> = ({ items = [], fields, handleRowClick = () => {} }) => {
  if (!items.length) return <div className="text-center p-6">No data</div>;
  return (
    <table className="table-auto w-full">
      <thead>
        <tr className="border-b select-none">
          {fields.map(field => <th className="pl-3 text-left bg-gray-100" key={field.label}>{field.label}</th>)}
        </tr>
      </thead>
      <tbody>
        {items.map((item, index) => (
          <tr
            key={item._id}
            className={`border-b hover:bg-gray-100 cursor-pointer ${index % 2 && 'bg-gray-50'}`}
            onClick={() => handleRowClick(index)}
          >
            {fields.map(field => (
              <td key={`${item._id} ${field.label}`} className="p-3">
                {getItemField(item, field)}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default ListTable;