Created
April 24, 2020 20:37
-
-
Save svsh227/8ffe2b9d8701240b245eadd0a637621b to your computer and use it in GitHub Desktop.
Create a component "TypeAheadDropDown.js": Now it's time to create our component, create a file "TypeAheadDropDown.js" inside "src" folder and write the below code: src/TypeAheadDropDown.js:
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
// TypeAheadDropDown.js | |
import './TypeAheadDropDown.css' | |
import React from 'react'; | |
export default class TypeAheadDropDown extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
suggestions: [], | |
text:'' | |
} | |
} | |
onTextChange = (e) => { | |
const {iteams} = this.props; | |
let suggestions = []; | |
const value = e.target.value; | |
if (value.length > 0) { | |
const regex = new RegExp(`^${value}`, `i`); | |
suggestions = iteams.sort().filter(v => regex.test(v)); | |
} | |
this.setState(() => ({ | |
suggestions, | |
text:value | |
})); | |
} | |
suggestionSelected=(value)=>{ | |
this.setState(()=>({ | |
text:value, | |
suggestions:[] | |
})) | |
} | |
renderSuggestions = () => { | |
const { suggestions } = this.state; | |
console.log("suggestions :",suggestions); | |
if (suggestions.length === 0) { | |
return null; | |
} | |
return ( | |
<ul> | |
{suggestions.map(city => <li key={city} onClick={(e)=>this.suggestionSelected(city)}>{city}</li>)} | |
</ul> | |
) | |
} | |
render() { | |
const {text}=this.state | |
return ( | |
<div className="TypeAheadDropDown"> | |
<input onChange={this.onTextChange} placeholder="Search city name" value={text} type="text" /> | |
{this.renderSuggestions()} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment