-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathAutoCompleteText.js
50 lines (49 loc) · 1.16 KB
/
AutoCompleteText.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
import React from "react";
import "./AutoCompleteText.css";
class AutoCompleteText extends React.Component {
constructor(props) {
super(props);
this.state = {
suggestions: [],
text: ""
};
}
onTextChanged = e => {
const value = e.target.value;
let suggestions = [];
if (value.length > 0) {
const regex = new RegExp(`${value}`, `i`);
suggestions = this.items.sort().filter(v => regex.test(v));
}
this.setState(() => ({ suggestions, text: value }));
};
suggestionsSelected(value) {
this.setState(() => ({
text: value,
suggestions: []
}));
}
renderSuggestions() {
const { suggestions } = this.state;
if (suggestions.length === 0) {
return null;
}
return (
<ul>
{suggestions.map(item => (
<li onClick={() => this.suggestionsSelected(item)}>{item}</li>
))}
</ul>
);
}
render() {
const { text } = this.state;
return (
<div className="AutoCompleteText">
<input value={text} onChange={this.onTextChanged} type="text" />
{this.renderSuggestions()}
</div>
);
}
}
export default AutoCompleteText;