Skip to content

Instantly share code, notes, and snippets.

@laere
Created February 8, 2016 01:32
Show Gist options
  • Save laere/fdf671d2dbda9b9e9f78 to your computer and use it in GitHub Desktop.
Save laere/fdf671d2dbda9b9e9f78 to your computer and use it in GitHub Desktop.
var React = require('react');
var Search = React.createClass({
getInitialState: function() {
return {
value: '',
isExpanded: false
}
},
handleOnChange: function(e) {
this.setState({
value: e.target.value,
});
},
render: function() {
if (this.props.characters.length <= 0) {
return this.renderLoading();
} else {
return this.renderSearch();
}
},
renderLoading: function() {
return (
<div>
...loading data...
</div>
)
},
expandOnFocus: function() {
this.setState({isExpanded: !this.state.isExpanded});
},
expandOnBlur: function() {
this.setState({isExpanded: !this.state.isExpanded});
},
renderSearch: function() {
//Desired name equals input value
var desiredName = this.state.value;
//Filter through results array for matching name, return name if it exists.
var matchingResults = this.props.characters.results.filter(function(result) {
console.log(desiredName);
return result.name.toLowerCase().indexOf(desiredName) !== -1;
});
return (
<div>
<img className="search-icon" src="https://cdn3.iconfinder.com/data/icons/ecommerce-5/100/search-01-128.png" width="16px" height="16px" />
<input type="text" className="search" value={this.state.value} onChange={this.handleOnChange} onFocus={this.expandOnFocus} onBlur={this.expandOnBlur} />
{/*Return the name of each object*/}
{matchingResults.map(function(matchingResult, i) {
return (
<div value={this.state.isExpanded} className="list-of-names" key={i}>
<div className="name">{matchingResult.name}</div>
</div>
)
})}
</div>
);
}
});
module.exports = Search;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment