-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
SearchBox.tsx
55 lines (50 loc) · 1.17 KB
/
SearchBox.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 React from 'react';
import { useKey } from 'react-use';
import { ESC } from '@codesandbox/common/lib/utils/keycodes';
import { SearchElement, InputWrapper } from './elements';
type SearchProps = {
value: string;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
placeholder?: string;
};
export const SearchBox = ({
value,
onChange,
placeholder = 'Search',
}: SearchProps) => {
const inputEl = React.useRef<HTMLInputElement>();
useKey('/', () => {
if (inputEl.current) {
requestAnimationFrame(() => {
inputEl.current.focus();
});
}
});
const handleEsc = (evt: React.KeyboardEvent<HTMLInputElement>) => {
if (evt.keyCode === ESC && inputEl.current) {
evt.stopPropagation();
inputEl.current.blur();
}
};
return (
<form
noValidate
action=""
role="search"
onSubmit={e => {
e.preventDefault();
}}
>
<InputWrapper>
<SearchElement
placeholder={placeholder}
ref={inputEl}
value={value}
onChange={onChange}
onKeyDown={handleEsc}
type="search"
/>
</InputWrapper>
</form>
);
};