-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
102 lines (87 loc) · 2.04 KB
/
index.js
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
import React, { Component } from 'react';
import { debounce } from 'throttle-debounce';
export default class DebounceText extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
items: [],
// initial false
showResults: false,
};
this.debounced = debounce(500, this.fetch);
}
componentDidMount() {
const { initialValue } = this.props;
if (initialValue) {
this.setState({
value: initialValue
})
}
}
changeQuery(event) {
const { value } = event.target;
return this.setState(
{
value,
showResults: !!value.trim(),
},
() => {
this.debounced(this.state.value);
}
);
}
fetch(q) {
return this.props.fetch(q, items => {
return this.setState({
items,
showResults: !!items.length,
});
});
}
renderItem(item, i) {
return (
<li
className="react-debounce-text__results-item"
onClick={() => this.onSelect(item, i)}
key={i}
>
{this.props.renderItem(item, i)}
</li>
);
}
onFocus() {
const { items } = this.state;
return this.setState({
showResults: !!items.length,
});
}
onSelect(item, i) {
return this.setState({ showResults: false, value: item.value }, () => {
return this.props.onSelect(item, i);
});
}
render() {
const { value, items, showResults } = this.state;
const { placeholder = 'Type something here' } = this.props;
return (
<div className="react-debounce-text">
<input
type="text"
className="react-debounce-text__input"
placeholder={placeholder}
value={value}
onChange={this.changeQuery.bind(this)}
onFocus={this.onFocus.bind(this)}
/>
{showResults && (
<ul className="react-debounce-text__results">
{items.map((item, i) => {
return this.renderItem(item, i);
})}
</ul>
)}
</div>
);
}
}