Created
April 16, 2020 17:27
-
-
Save adamloving/455f8d198dd6bab048e9b14d7a126dbc to your computer and use it in GitHub Desktop.
React typeahead autocomplete
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { ActionMeta, ValueType } from "react-select"; | |
import CreatableSelect from "react-select/creatable"; | |
type CreatableMultiSelectProps = { | |
options: Set<string>; // available choices | |
values: Set<string>; // current selections | |
onChange: (values: Set<string>) => void; | |
}; | |
type Option = { | |
value: string; | |
label: string; | |
}; | |
const convertStringToOption = (value: string) => { | |
return { value, label: value }; | |
}; | |
// bugbug: converts "DJ" to "Dj" | |
const toTitleCase = (s: string) => { | |
return s.replace( | |
/\w\S*/g, | |
(m: string) => m.charAt(0).toUpperCase() + m.substr(1).toLowerCase() | |
); | |
}; | |
export default class CreatableMultiSelect extends React.Component<CreatableMultiSelectProps> { | |
handleChange = (value: ValueType<Option>, action: ActionMeta) => { | |
const values = value as Array<Option>; // could be a single Option for some types of action | |
const capitalizedSortedValues = values | |
.map((o) => toTitleCase(o.value)) | |
.sort(); | |
const uniqueValues = new Set<string>(capitalizedSortedValues); | |
this.props.onChange(uniqueValues); | |
}; | |
render() { | |
const options = Array.from(this.props.options).map(convertStringToOption); | |
const value = Array.from(this.props.values).map(convertStringToOption); | |
return ( | |
<CreatableSelect<Option> | |
isMulti | |
isClearable | |
value={value} | |
onChange={this.handleChange} | |
options={options} | |
/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment