-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathSearch.tsx
65 lines (53 loc) · 1.43 KB
/
Search.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
import React from 'react';
import {TextInput} from '@gravity-ui/uikit';
import {cn} from '../../utils/cn';
import './Search.scss';
const b = cn('ydb-search');
interface SearchProps {
onChange: (value: string) => void;
value?: string;
width?: React.CSSProperties['width'];
className?: string;
debounce?: number;
placeholder?: string;
inputRef?: React.RefObject<HTMLInputElement>;
}
export const Search = ({
onChange,
value = '',
width,
className,
debounce = 200,
placeholder,
inputRef,
}: SearchProps) => {
const [searchValue, setSearchValue] = React.useState<string>(value);
const timer = React.useRef<number>();
React.useEffect(() => {
setSearchValue((prevValue) => {
if (prevValue !== value) {
return value;
}
return prevValue;
});
}, [value]);
const onSearchValueChange = (newValue: string) => {
setSearchValue(newValue);
window.clearTimeout(timer.current);
timer.current = window.setTimeout(() => {
onChange?.(newValue);
}, debounce);
};
return (
<TextInput
hasClear
autoFocus
controlRef={inputRef}
style={{width}}
className={b(null, className)}
placeholder={placeholder}
value={searchValue}
onUpdate={onSearchValueChange}
/>
);
};