-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypeahead-react.js
More file actions
95 lines (87 loc) · 2.59 KB
/
Copy pathtypeahead-react.js
File metadata and controls
95 lines (87 loc) · 2.59 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
'use strict';
var React = require('react');
var Typeahead = React.createClass({
displayName: 'Typeahead',
getInitialState: function getInitialState() {
return {
values: this.props.values ? this.props.values : [],
list: [],
label_key: this.props.label_key,
value_key: this.props.value_key
};
},
componentWillReceiveProps: function componentWillReceiveProps(newProps) {
this.setState({
values: newProps.values ? newProps.values : {},
label_key: this.props.label_key,
value_key: this.props.value_key
});
},
formUpdate: function formUpdate(e) {
var search = e.target.value.toLowerCase();
this.state.selected = {};
this.filterList(search);
},
onKeyUp: function onKeyUp(e) {
if (e.keyCode === 13) {
if (this.state.list.length) {
this.select(this.state.list[0]);
}
}
},
filterList: function filterList(search) {
var list = [];
if (search && search.length) {
this.state.values.map(function (val) {
var label = this.state.label_key ? val[this.state.label_key] : val;
if (typeof label === 'string') {
label = label.toLowerCase();
}
if (label.indexOf(search) !== -1) {
list.push(val);
}
}, this);
}
this.state.list = list;
this.forceUpdate();
},
select: function select(val) {
var input = document.getElementById(this.props.id + '__typeahead_field');
input.value = this.state.label_key ? val[this.state.label_key] : val;
this.state.selected = this.state.value_key ? val[this.state.value_key] : val;
this.state.list = [];
if (this.props.onSelect) {
this.props.onSelect(this.state.selected);
}
this.forceUpdate();
},
render: function render() {
var style = {
display: this.state.list.length ? 'block' : 'none',
position: 'relative',
padding: '5px'
};
var context = this;
return React.createElement(
'div',
{ id: this.props.id + "__typeahead_form", className: 'form-group', onBlur: this.inputBlur },
React.createElement('input', { type: 'text', id: this.props.id + "__typeahead_field", className: 'form-control', onChange: this.formUpdate, onKeyUp: this.onKeyUp }),
React.createElement(
'ul',
{ id: this.props.id + "__typeahead_list", tabIndex: '-1', className: 'dropdown-menu', style: style },
context.state.list.map(function (val) {
return React.createElement(
'li',
{ key: context.state.value_key ? val[context.state.value_key] : val },
React.createElement(
'a',
{ href: '#', onClick: context.select.bind(null, val) },
context.state.label_key ? val[context.state.label_key] : val
)
);
})
)
);
}
});
module.exports = Typeahead;