Last active
September 25, 2018 19:02
-
-
Save lavelle/31adaab59b9e142e850d4d4b3aa39da9 to your computer and use it in GitHub Desktop.
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
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import _ from 'lodash'; | |
import './style.css'; | |
const RATE_LIMIT = 500; | |
class Autocomplete extends React.Component { | |
constructor(props) { | |
super(props); | |
console.log('constructor', 'test'); | |
this.onChange = this.onChange.bind(this); | |
this.onItemClick = this.onItemClick.bind(this); | |
this.onBlur = this.onBlur.bind(this); | |
this.makeQuery = _.throttle(this.makeQuery, RATE_LIMIT); | |
this.state = { | |
isDropdownOpen: false, | |
results: [], | |
value: '', | |
}; | |
} | |
makeQuery(query) { | |
fetch(`https://mock-autocomplete.herokuapp.com/autocomplete?q=${query}`).then(data => { | |
return data.json(); | |
}).then(data => { | |
this.setState({ results: data.data }); | |
}); | |
} | |
onChange(event) { | |
this.setState({ | |
value: event.target.value, | |
isDropdownOpen: true, | |
}); | |
this.makeQuery(event.target.value); | |
} | |
onItemClick(item) { | |
this.setState({ | |
value: item, | |
results: [], | |
}); | |
} | |
onBlur(event) { | |
if (_.get(event, 'relatedTarget.id') !== 'dropdown') { | |
this.setState({ | |
isDropdownOpen: false | |
}); | |
} | |
} | |
render() { | |
return ( | |
<div className="autocomplete"> | |
<form> | |
<input type="text" id="search" onChange={this.onChange} value={this.state.value} onBlur={this.onBlur} /> | |
</form> | |
{this.state.isDropdownOpen && | |
<div id="results"> | |
<ul tabIndex="0" id="dropdown"> | |
{_.map(this.state.results, result => ( | |
<li key={result} onClick={() => this.onItemClick(result)} className="item"> | |
{result} | |
</li> | |
))} | |
</ul> | |
</div> | |
} | |
</div> | |
); | |
} | |
} | |
ReactDOM.render(<Autocomplete />, document.getElementById('root')); |
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
h1, p { | |
font-family: Lato; | |
} | |
ul { | |
margin: 0; | |
padding: 0; | |
} | |
.autocomplete { | |
max-width: 500px; | |
} | |
.item { | |
list-style-type: none; | |
border: 1px solid gray; | |
cursor: pointer; | |
margin: 0; | |
padding: 5px; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment