/
index.tsx
executable file
路94 lines (82 loc) 路 2.39 KB
/
index.tsx
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import * as React from 'react'
export * from '@tanstack/table-core'
import {
TableOptions,
TableOptionsResolved,
RowData,
createTable,
} from '@tanstack/table-core'
export type Renderable<TProps> = React.ReactNode | React.ComponentType<TProps>
//
/**
* If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.
*/
export function flexRender<TProps extends object>(
Comp: Renderable<TProps>,
props: TProps
): React.ReactNode | JSX.Element {
return !Comp ? null : isReactComponent<TProps>(Comp) ? (
<Comp {...props} />
) : (
Comp
)
}
function isReactComponent<TProps>(
component: unknown
): component is React.ComponentType<TProps> {
return (
isClassComponent(component) ||
typeof component === 'function' ||
isExoticComponent(component)
)
}
function isClassComponent(component: any) {
return (
typeof component === 'function' &&
(() => {
const proto = Object.getPrototypeOf(component)
return proto.prototype && proto.prototype.isReactComponent
})()
)
}
function isExoticComponent(component: any) {
return (
typeof component === 'object' &&
typeof component.$$typeof === 'symbol' &&
['react.memo', 'react.forward_ref'].includes(component.$$typeof.description)
)
}
export function useReactTable<TData extends RowData>(
options: TableOptions<TData>
) {
// Compose in the generic options to the user options
const resolvedOptions: TableOptionsResolved<TData> = {
state: {}, // Dummy state
onStateChange: () => {}, // noop
renderFallbackValue: null,
...options,
}
// Create a new table and store it in state
const [tableRef] = React.useState(() => ({
current: createTable<TData>(resolvedOptions),
}))
// By default, manage table state here using the table's initial state
const [state, setState] = React.useState(() => tableRef.current.initialState)
// Compose the default state above with any user state. This will allow the user
// to only control a subset of the state if desired.
tableRef.current.setOptions(prev => ({
...prev,
...options,
state: {
...state,
...options.state,
},
// Similarly, we'll maintain both our internal state and any user-provided
// state.
onStateChange: updater => {
setState(updater)
options.onStateChange?.(updater)
},
}))
return tableRef.current
}