Skip to content

Instantly share code, notes, and snippets.

@tgandrews
Last active September 7, 2018 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgandrews/2f00fb1823d52f8767729d91355a462a to your computer and use it in GitHub Desktop.
Save tgandrews/2f00fb1823d52f8767729d91355a462a to your computer and use it in GitHub Desktop.
import React from "react";
import PropTypes from "prop-types";
import Downshift from "downshift";
class Typeahead extends React.Component {
state = {
value: null
};
handleStateChange = changes => {
let value;
if (changes.hasOwnProperty("selectedItem")) {
value = changes.selectedItem;
} else if (changes.hasOwnProperty("inputValue")) {
value = changes.inputValue;
}
// Could remove if you checked if you got one of inputValue or selectedItem as it seems to get a number of other events
if (value === undefined) {
return;
}
this.setState(() => {
this.props.onChange(value);
return { value };
});
};
render() {
const { onChange, ...otherProps } = this.props;
return (
<Downshift
itemToString={item => (item ? item.value : "")}
onStateChange={this.handleStateChange}
selectedItem={this.state.value}
{...otherProps}
/>
);
}
}
Typeahead.propTypes = {
onChange: PropTypes.func.isRequired
};
export default Typeahead;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment