Created
December 13, 2016 08:21
-
-
Save adrianmcli/67e29eab8ac839c4011e70d92a1c08d2 to your computer and use it in GitHub Desktop.
Dead simple react-autosuggest 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
import React from 'react'; | |
import Autosuggest from 'react-autosuggest'; | |
// This function returns the suggestions, given the current input value. | |
function getSuggestions(value) { | |
// I decided to always return the same suggestions | |
// just to keep things simple. | |
return [ | |
{ name: 'a' }, | |
{ name: 'aa' }, | |
{ name: 'aab' }, | |
{ name: 'b' }, | |
{ name: 'bb' }, | |
{ name: 'bbc' }, | |
]; | |
} | |
// How each suggested item will be rendered | |
function renderSuggestion(suggestion) { | |
return <span>{suggestion.name}</span>; | |
} | |
// What should be the input value (for the textbox), when a suggested item is selected | |
function getSuggestionValue(suggestion) { | |
return suggestion.name; | |
} | |
export default class Component extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
value: '', | |
suggestions: [], | |
}; | |
} | |
onChange = (event, { newValue }) => | |
this.setState({ value: newValue }); | |
// Grab new suggestions and load them into the state | |
onSuggestionsFetchRequested = ({ value }) => | |
this.setState({ suggestions: getSuggestions(value) }); | |
// Clear all suggestions | |
onSuggestionsClearRequested = () => | |
this.setState({ suggestions: [] }); | |
render() { | |
const { value, suggestions } = this.state; | |
const inputProps = { | |
placeholder: 'Type something', | |
onChange: this.onChange, | |
value, | |
}; | |
return ( | |
<Autosuggest | |
suggestions={suggestions} | |
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} | |
onSuggestionsClearRequested={this.onSuggestionsClearRequested} | |
getSuggestionValue={getSuggestionValue} | |
renderSuggestion={renderSuggestion} | |
inputProps={inputProps} | |
/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment