Skip to content

Instantly share code, notes, and snippets.

@dengue8830
Last active May 23, 2018 16:50
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 dengue8830/b83fc4794c210ee7b5d62461b631fd79 to your computer and use it in GitHub Desktop.
Save dengue8830/b83fc4794c210ee7b5d62461b631fd79 to your computer and use it in GitHub Desktop.
Simple react typeahead component
// Works with this typeahead https://github.com/bassjobsen/Bootstrap-3-Typeahead
// but its easy to change to another lib
import * as React from 'react';
const $ = window.$;
export interface SearchParams {
query: string;
callback: (items: any) => void;
}
interface SearchBoxProps {
onSelected: (item: any) => void;
onSearch: (params: SearchParams) => void;
display: string;
placeholder?: string;
className?: string;
startingValue?: string;
}
export class SearchBox extends React.Component<SearchBoxProps, any> {
input: HTMLInputElement | null;
clear() {
$(this.input).val('');
}
componentDidMount() {
if (this.props.startingValue) {
$(this.input).val(this.props.startingValue);
}
$(this.input).typeahead({
changeInputOnSelect: true,
afterSelect: (item: any) => {
this.props.onSelected(item);
},
displayText: (item: any) => item.nombre,
source: (query: string, cb: (cb: any) => void) => {
this.props.onSearch({ query: query, callback: cb });
},
items: 'all'
});
}
focus() {
if (this.input) {
this.input.focus();
}
}
render() {
return (
<input
type="text"
className={'form-control' + (this.props.className ? ' ' + this.props.className : '')}
ref={ref => this.input = ref}
placeholder={this.props.placeholder} />
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment