Last active
March 25, 2018 22:24
-
-
Save pinglinh/b75c64c90b6f77c04cfeae0a82e4e942 to your computer and use it in GitHub Desktop.
Refactoring React components : start
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
import React from "react"; | |
export class Search extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
value: "", | |
articles: [] | |
}; | |
this.handleChange = this.handleChange.bind(this); | |
this.handleSubmit = this.handleSubmit.bind(this); | |
} | |
handleChange(event) { | |
this.setState({ value: event.target.value }); | |
fetch(`http://content.guardianapis.com/search?q=${event.target.value}&api-key=YOUR_API_KEY`) | |
.then(response => response.json()) | |
.then(data => this.setState({ articles: data.response.results })); | |
} | |
handleSubmit(event) { | |
event.preventDefault(); | |
} | |
render() { | |
return ( | |
<div> | |
<h1>The Guardian Search App</h1> | |
<form onSubmit={this.handleSubmit}> | |
<input | |
type="text" | |
value={this.state.value} | |
onChange={this.handleChange} | |
/> | |
</form> | |
<div> | |
{this.state.articles.map((article, index) => { | |
return <li key={index}><a href={article.webUrl} target="_blank">{article.webTitle}</a></li> | |
})} | |
</div> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment