Skip to content

Instantly share code, notes, and snippets.

@svsh227
Created April 24, 2020 20:37
Show Gist options
  • Save svsh227/8ffe2b9d8701240b245eadd0a637621b to your computer and use it in GitHub Desktop.
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:
// 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