Created
September 6, 2019 06:32
-
-
Save prashanth-sams/2ecab634b393a5aa8fd2283105c1569f to your computer and use it in GitHub Desktop.
Auto-suggestion
This file contains hidden or 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
| 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