|
1
|
|
|
import React, { useState } from 'react'; |
|
2
|
|
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; |
|
3
|
|
|
import { faSearch as searchIcon } from '@fortawesome/free-solid-svg-icons'; |
|
4
|
|
|
import PropTypes from 'prop-types'; |
|
5
|
|
|
import classNames from 'classnames'; |
|
6
|
|
|
import './SearchField.scss'; |
|
7
|
|
|
|
|
8
|
4 |
|
const DEFAULT_SEARCH_INTERVAL = 500; |
|
9
|
|
|
let timer; |
|
10
|
|
|
|
|
11
|
4 |
|
const propTypes = { |
|
12
|
|
|
onChange: PropTypes.func.isRequired, |
|
13
|
|
|
className: PropTypes.string, |
|
14
|
|
|
placeholder: PropTypes.string, |
|
15
|
|
|
large: PropTypes.bool, |
|
16
|
|
|
noBorder: PropTypes.bool, |
|
17
|
|
|
}; |
|
18
|
|
|
|
|
19
|
4 |
|
const SearchField = ({ onChange, className, placeholder = 'Search...', large = true, noBorder = false }) => { |
|
20
|
|
|
const [ searchTerm, setSearchTerm ] = useState(''); |
|
21
|
|
|
|
|
22
|
|
|
const resetTimer = () => { |
|
23
|
|
|
clearTimeout(timer); |
|
24
|
|
|
timer = null; |
|
25
|
|
|
}; |
|
26
|
1 |
|
const searchTermChanged = (newSearchTerm, timeout = DEFAULT_SEARCH_INTERVAL) => { |
|
27
|
|
|
setSearchTerm(newSearchTerm); |
|
28
|
|
|
|
|
29
|
|
|
resetTimer(); |
|
30
|
|
|
|
|
31
|
|
|
timer = setTimeout(() => { |
|
32
|
|
|
onChange(newSearchTerm); |
|
33
|
|
|
resetTimer(); |
|
34
|
|
|
}, timeout); |
|
35
|
|
|
}; |
|
36
|
|
|
|
|
37
|
|
|
return ( |
|
38
|
|
|
<div className={classNames('search-field', className)}> |
|
39
|
|
|
<input |
|
40
|
|
|
type="text" |
|
41
|
|
|
className={classNames('form-control search-field__input', { |
|
42
|
|
|
'form-control-lg': large, |
|
43
|
|
|
'search-field__input--no-border': noBorder, |
|
44
|
|
|
})} |
|
45
|
|
|
placeholder={placeholder} |
|
46
|
|
|
value={searchTerm} |
|
47
|
|
|
onChange={(e) => searchTermChanged(e.target.value)} |
|
48
|
|
|
/> |
|
49
|
|
|
<FontAwesomeIcon icon={searchIcon} className="search-field__icon" /> |
|
50
|
|
|
<div |
|
51
|
|
|
className="close search-field__close" |
|
52
|
|
|
hidden={searchTerm === ''} |
|
53
|
|
|
id="search-field__close" |
|
54
|
|
|
onClick={() => searchTermChanged('', 0)} |
|
55
|
|
|
> |
|
56
|
|
|
× |
|
57
|
|
|
</div> |
|
58
|
|
|
</div> |
|
59
|
|
|
); |
|
60
|
|
|
}; |
|
61
|
|
|
|
|
62
|
4 |
|
SearchField.propTypes = propTypes; |
|
63
|
|
|
|
|
64
|
|
|
export default SearchField; |
|
65
|
|
|
|