forked from Kuechlin/mantine-data-grid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlobalFilter.tsx
55 lines (46 loc) · 1.75 KB
/
GlobalFilter.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
import { TextInput } from '@mantine/core';
import { IconSearch } from '@tabler/icons-react';
import { FilterFn, Table } from '@tanstack/react-table';
import { isValidElement, useEffect, useState } from 'react';
import { renderToString } from 'react-dom/server';
import { DataGridLocale } from './types';
type GlobalFilterProps<TData> = {
table: Table<TData>;
className: string;
locale?: DataGridLocale;
};
export function GlobalFilter<TData>({ table, className, locale }: GlobalFilterProps<TData>) {
const globalFilter = table.getState().globalFilter;
const [value, setValue] = useState(globalFilter || '');
useEffect(() => {
setValue(globalFilter || '');
}, [globalFilter]);
useEffect(() => {
const timeout = setTimeout(() => {
table.setGlobalFilter(value);
}, 200);
return () => clearTimeout(timeout);
}, [table, value]);
return (
<TextInput
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={locale?.globalSearch || 'Search...'}
rightSection={<IconSearch />}
className={className}
/>
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const globalFilterFn: FilterFn<any> = (row, columnId: string, filterValue: string) => {
const value = row.getValue<string>(columnId);
if (!value) return false;
// if is a react element, then render it to string, so it can be searched
if (isValidElement(value)) {
const htmlString = renderToString(value);
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
return (doc.body.textContent || doc.body.innerText).toLowerCase().includes(filterValue.toLowerCase());
}
return value.toString().toLowerCase().includes(filterValue.toString().toLowerCase());
};