aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/ui/SearchInput.js
blob: 2e8793a2bd6f6fb9396e9f36daea5ffd38f85bf2 (plain) (blame)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import classnames from 'classnames';
import { debounce } from 'lodash';

@observer
class SearchInput extends Component {
  static propTypes = {
    value: PropTypes.string,
    placeholder: PropTypes.string,
    className: PropTypes.string,
    onChange: PropTypes.func,
    onReset: PropTypes.func,
    name: PropTypes.string,
    throttle: PropTypes.bool,
    throttleDelay: PropTypes.number,
    autoFocus: PropTypes.bool,
  };

  static defaultProps = {
    value: '',
    placeholder: '',
    className: '',
    name: 'searchInput',
    throttle: false,
    throttleDelay: 250,
    onChange: () => null,
    onReset: () => null,
    autoFocus: false,
  };

  input = null;

  constructor(props) {
    super(props);

    this.state = {
      value: props.value,
    };

    this.throttledOnChange = debounce(
      this.throttledOnChange,
      this.props.throttleDelay,
    );
  }

  componentDidMount() {
    const { autoFocus } = this.props;

    if (autoFocus) {
      this.input.focus();
    }
  }

  onChange(e) {
    const { throttle, onChange } = this.props;
    const { value } = e.target;
    this.setState({ value });

    if (throttle) {
      e.persist();
      this.throttledOnChange(value);
    } else {
      onChange(value);
    }
  }

  throttledOnChange(e) {
    const { onChange } = this.props;

    onChange(e);
  }

  reset() {
    const { onReset } = this.props;
    this.setState({ value: '' });

    onReset();
  }

  render() {
    const { className, name, placeholder } = this.props;
    const { value } = this.state;

    return (
      <div className={classnames([className, 'search-input'])}>
        <label htmlFor={name} className="mdi mdi-magnify">
          <input
            name={name}
            id={name}
            type="text"
            placeholder={placeholder}
            value={value}
            onChange={e => this.onChange(e)}
            ref={ref => {
              this.input = ref;
            }}
          />
        </label>
        {value.length > 0 && (
          <span
            className="mdi mdi-close-circle-outline"
            onClick={() => this.reset()}
          />
        )}
      </div>
    );
  }
}

export default SearchInput;