-
-
Notifications
You must be signed in to change notification settings - Fork 503
Expand file tree
/
Copy pathDropdown.jsx
More file actions
98 lines (85 loc) · 2.57 KB
/
Dropdown.jsx
File metadata and controls
98 lines (85 loc) · 2.57 KB
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
import { createRef } from "preact";
import PropTypes from "prop-types";
import PureComponent from "../lib/PureComponent.jsx";
import * as styles from "./Dropdown.css";
export default class Dropdown extends PureComponent {
static propTypes = {
label: PropTypes.string.isRequired,
options: PropTypes.arrayOf(PropTypes.string).isRequired,
onSelectionChange: PropTypes.func.isRequired,
};
input = createRef();
state = {
query: "",
showOptions: false,
};
componentDidMount() {
document.addEventListener("click", this.handleClickOutside, true);
}
componentWillUnmount() {
document.removeEventListener("click", this.handleClickOutside, true);
}
render() {
const { label, options } = this.props;
const filteredOptions = this.state.query
? options.filter((option) =>
option.toLowerCase().includes(this.state.query.toLowerCase()),
)
: options;
return (
<div className={styles.container}>
<div className={styles.label}>{label}:</div>
<div>
<input
ref={this.input}
className={styles.input}
type="text"
value={this.state.query}
onInput={this.handleInput}
onFocus={this.handleFocus}
/>
{this.state.showOptions ? (
<div>
{filteredOptions.map((option) => (
<div
key={option}
className={styles.option}
onClick={this.getOptionClickHandler(option)}
>
{option}
</div>
))}
</div>
) : null}
</div>
</div>
);
}
handleClickOutside = (event) => {
const el = this.input.current;
if (el && event && !el.contains(event.target)) {
this.setState({ showOptions: false });
// If the query is not in the options, reset the selection
if (this.state.query && !this.props.options.includes(this.state.query)) {
this.setState({ query: "" });
this.props.onSelectionChange(undefined);
}
}
};
handleInput = (event) => {
const { value } = event.target;
this.setState({ query: value });
if (!value) {
this.props.onSelectionChange(undefined);
}
};
handleFocus = () => {
// move the cursor to the end of the input
this.input.current.value = this.state.query;
this.setState({ showOptions: true });
};
getOptionClickHandler = (option) => () => {
this.props.onSelectionChange(option);
this.setState({ query: option, showOptions: false });
};
}