Passed
Pull Request — master (#163)
by Alejandro
06:15
created

src/utils/SearchField.js   A

Complexity

Total Complexity 2
Complexity/F 1

Size

Lines of Code 68
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 17.65%

Importance

Changes 0
Metric Value
wmc 2
eloc 56
mnd 0
bc 0
fnc 2
dl 0
loc 68
ccs 3
cts 17
cp 0.1765
rs 10
bpm 0
cpm 1
noi 0
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A SearchField.searchTermChanged 0 18 1
A SearchField.render 0 23 1
1
import React 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 2
const DEFAULT_SEARCH_INTERVAL = 500;
9
10
export default class SearchField extends React.Component {
11 2
  static propTypes = {
12
    onChange: PropTypes.func.isRequired,
13
    className: PropTypes.string,
14
    placeholder: PropTypes.string,
15
  };
16 2
  static defaultProps = {
17
    className: '',
18
    placeholder: 'Search...',
19
  };
20
21
  state = { showClearBtn: false, searchTerm: '' };
22
  timer = null;
23
24
  searchTermChanged(searchTerm, timeout = DEFAULT_SEARCH_INTERVAL) {
25
    this.setState({
26
      showClearBtn: searchTerm !== '',
27
      searchTerm,
28
    });
29
30
    const resetTimer = () => {
31
      clearTimeout(this.timer);
32
      this.timer = null;
33
    };
34
35
    resetTimer();
36
37
    this.timer = setTimeout(() => {
38
      this.props.onChange(searchTerm);
39
      resetTimer();
40
    }, timeout);
41
  }
42
43
  render() {
44
    const { className, placeholder } = this.props;
45
46
    return (
47
      <div className={classnames('search-field', className)}>
48
        <input
49
          type="text"
50
          className="form-control form-control-lg search-field__input"
51
          placeholder={placeholder}
52
          value={this.state.searchTerm}
53
          onChange={(e) => this.searchTermChanged(e.target.value)}
54
        />
55
        <FontAwesomeIcon icon={searchIcon} className="search-field__icon" />
56
        <div
57
          className="close search-field__close"
58
          hidden={!this.state.showClearBtn}
59
          id="search-field__close"
60
          onClick={() => this.searchTermChanged('', 0)}
61
        >
62
          &times;
63
        </div>
64
      </div>
65
    );
66
  }
67
}
68