Skip to content

Instantly share code, notes, and snippets.

@adamloving
Created April 16, 2020 17:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save adamloving/455f8d198dd6bab048e9b14d7a126dbc to your computer and use it in GitHub Desktop.
React typeahead autocomplete
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