maputnik/src/components/inputs/AutocompleteInput.jsx

90 lines
2 KiB
React
Raw Normal View History

import React from 'react'
import PropTypes from 'prop-types'
2017-01-11 14:03:48 +01:00
import classnames from 'classnames'
import Autocomplete from 'react-autocomplete'
2017-01-11 14:03:48 +01:00
2017-11-29 11:29:11 +01:00
const MAX_HEIGHT = 140;
2018-01-19 12:50:23 +01:00
class AutocompleteInput extends React.Component {
static propTypes = {
2018-01-19 12:50:23 +01:00
value: PropTypes.string,
options: PropTypes.array,
onChange: PropTypes.func,
keepMenuWithinWindowBounds: PropTypes.bool
}
static defaultProps = {
onChange: () => {},
options: [],
}
constructor(props) {
super(props);
this.state = {
maxHeight: MAX_HEIGHT
};
}
calcMaxHeight() {
if(this.props.keepMenuWithinWindowBounds) {
const maxHeight = window.innerHeight - this.autocompleteMenuEl.getBoundingClientRect().top;
2017-11-29 11:29:11 +01:00
const limitedMaxHeight = Math.min(maxHeight, MAX_HEIGHT);
if(limitedMaxHeight != this.state.maxHeight) {
this.setState({
2017-11-29 11:29:11 +01:00
maxHeight: limitedMaxHeight
})
}
}
}
componentDidMount() {
this.calcMaxHeight();
}
componentDidUpdate() {
this.calcMaxHeight();
}
render() {
2018-01-19 12:50:23 +01:00
return <div
ref={(el) => {
this.autocompleteMenuEl = el;
}}
2018-01-19 12:50:23 +01:00
>
<Autocomplete
menuStyle={{
position: "absolute",
overflow: "auto",
maxHeight: this.state.maxHeight
}}
wrapperProps={{
className: "maputnik-autocomplete",
style: null
}}
inputProps={{
className: "maputnik-string"
}}
value={this.props.value}
items={this.props.options}
getItemValue={(item) => item[0]}
onSelect={v => this.props.onChange(v)}
onChange={(e, v) => this.props.onChange(v)}
renderItem={(item, isHighlighted) => (
<div
key={item[0]}
className={classnames({
"maputnik-autocomplete-menu-item": true,
"maputnik-autocomplete-menu-item-selected": isHighlighted,
})}
>
{item[1]}
</div>
)}
/>
</div>
}
}
export default AutocompleteInput