Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15312 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
15310 stevensc 1
/* eslint-disable no-mixed-spaces-and-tabs */
2
import React from 'react'
3
import { useEffect } from 'react'
4
import { useCallback } from 'react'
5
import { useState } from 'react'
6
 
7
const sortData = ({ tableData, sortKey, reverse }) => {
8
	let sortedData
9
 
10
	if (!sortKey) return tableData
11
 
12
	tableData
13
	sortedData = tableData.sort((a, b) => {
14
		if (typeof a[sortKey] === 'string') {
15
			return a[sortKey].toLowerCase() < b[sortKey].toLowerCase() && -1
16
		}
17
 
18
		return a[sortKey] - b[sortKey]
19
	})
20
 
21
 
22
	if (reverse) return sortedData.reverse()
23
 
24
	return sortedData
25
}
26
 
27
const SortButton = ({ reverse, columnKey, sortKey, onClick }) => {
28
	return (
29
		<button onClick={onClick} className="btn p-0">
30
			{
31
				(sortKey === columnKey) && reverse
32
					? <i className='fa fa-angle-up ml-2' />
33
					: <i className='fa fa-angle-down ml-2' />
34
			}
35
		</button>
36
	)
37
}
38
 
39
const Table = ({ data = [], headers, setData, children }) => {
40
 
41
	const [sortKey, setSortKey] = useState('name')
42
	const [reverse, setReverse] = useState(false)
43
 
44
	const sortedData = useCallback(
45
		() => sortData({ tableData: data, sortKey, reverse: reverse }),
46
		[data, sortKey, reverse]
47
	)
48
 
49
	const changeSort = (key) => {
50
		setReverse(!reverse)
51
		setSortKey(key)
52
	}
53
 
54
	useEffect(() => {
55
		setData(sortedData())
56
	}, [sortKey, reverse])
57
 
58
	return (
59
		<table className="table table-hover my-table w-100">
60
			<thead>
61
				<tr>
62
					{headers.map((row) =>
63
						<th key={row.key} className="text-vertical-middle">
64
							{row.label}
65
							{row.isSorteable &&
66
                                <SortButton
67
                                	columnKey={row.key}
68
                                	onClick={() => changeSort(row.key)}
69
                                	sortKey={sortKey}
70
                                	reverse={reverse}
71
                                />
72
							}
73
						</th>
74
					)}
75
				</tr>
76
			</thead>
77
			<tbody>
78
				{children()}
79
			</tbody>
80
		</table >
81
	)
82
}
83
 
84
export default Table