summaryrefslogtreecommitdiff
path: root/src/components/ListTable.tsx
blob: e90d2db61efcc8198bfccaef19847b82edb1b773 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import React, { useState, useMemo, useCallback } from 'react';
import _ from 'lodash';

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

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

const sortLabels = {
  asc: '^',
  desc: 'v',
};

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 = () => {} }) => {
  const [sortBy, setSortBy] = useState<string>('');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');

  const sortedItems = useMemo(() => {
    const result = _.sortBy(items, sortBy);
    if (sortOrder === 'asc') result.reverse();
    return result;
  }, [items, sortBy, sortOrder]);

  const handleFieldClick = useCallback((field: Field) => {
    if (sortBy === field.key) setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    else setSortOrder('desc');
    setSortBy(field.key);
  }, [sortBy, sortOrder]);

  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} onClick={() => handleFieldClick(field)}>
              {field.label} {field.key === sortBy && sortLabels[sortOrder]}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {sortedItems.map((item, index) => (
          <tr
            key={item._id}
            className={`border-b hover:bg-gray-100 cursor-pointer ${index % 2 && 'bg-gray-50'}`}
            onClick={() => handleRowClick(item, index)}
          >
            {fields.map(field => (
              <td key={`${item._id} ${field.label}`} className="p-3">
                {getItemField(item, field)}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default ListTable;