Created
March 26, 2018 15:02
-
-
Save pinglinh/fd57156944fa8801ea5fe69707500b49 to your computer and use it in GitHub Desktop.
Refactoring React components : 1.3
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"; | |
import SearchResult from "../SearchResult"; | |
const Search = props => { | |
return ( | |
<div> | |
<h1>The Guardian Search App</h1> | |
<form onSubmit={props.handleSubmit}> | |
<input | |
type="text" | |
value={props.value} | |
onChange={props.performSearch} /> | |
</form> | |
<div> | |
{props.articles.map((article, index) => { | |
return <SearchResult key={index} result={article} />; | |
})} | |
</div> | |
</div> | |
); | |
}; | |
export default Search; |
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"; | |
import Search from "../../components/Search"; | |
class SearchContainer 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 ( | |
<Search | |
handleSubmit={this.handleSubmit} | |
value={this.state.value} | |
performSearch={this.handleChange} | |
articles={this.state.articles} | |
/> | |
); | |
} | |
} | |
export default SearchContainer; |
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"; | |
const SearchResult = props => { | |
return ( | |
<div className={style.eachResult}> | |
<ul> | |
<li> | |
<a href={props.result.webUrl} target="_blank"> | |
{props.result.webTitle} | |
</a> | |
</li> | |
</ul> | |
</div> | |
); | |
}; | |
export default SearchResult; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment