Skip to content

Instantly share code, notes, and snippets.

@prashanth-sams
Created September 6, 2019 06:32
Show Gist options
  • Select an option

  • Save prashanth-sams/2ecab634b393a5aa8fd2283105c1569f to your computer and use it in GitHub Desktop.

Select an option

Save prashanth-sams/2ecab634b393a5aa8fd2283105c1569f to your computer and use it in GitHub Desktop.
Auto-suggestion
constructor(props){
super(props);
this.items = [
'David',
'Sara',
'Jane',
'Daniel',
'Debra'
];
this.state = {
suggesstions: []
};
}
onTextChange = (e) => {
// console.log(e.target.value);
const value = e.target.value;
let suggesstions = [];
if (value.length > 0) {
const regex = new RegExp(`^${value}`, 'i');
suggesstions = this.items.sort().filter(v => regex.test(v));
}
this.setState(() => ({ suggesstions }));
}
renderSuggestions () {
const { suggesstions } = this.state;
if (suggesstions.length == 0) {
return null;
}
return (
<ul>
{suggesstions.map((item) => <li>{item}</li>)}
</ul>
);
}
render(){
return (
<input onChange={this.onTextChange} type="text" />
{this.renderSuggestions()}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment