Last active
May 23, 2018 16:50
-
-
Save dengue8830/b83fc4794c210ee7b5d62461b631fd79 to your computer and use it in GitHub Desktop.
Simple react typeahead component
This file contains 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
// 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