Skip to content

Instantly share code, notes, and snippets.

@pinglinh
Last active March 26, 2018 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinglinh/a6c2c1748ddeaa54acfd459d4e56ec9d to your computer and use it in GitHub Desktop.
Save pinglinh/a6c2c1748ddeaa54acfd459d4e56ec9d to your computer and use it in GitHub Desktop.
Refactoring React components : 1.2
import React from "react";
import SearchResult from "./SearchResult";
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 <SearchResult key={index} result={article}/>
})}
</div>
</div>
);
}
}
import React from "react";
const SearchResult = props => {
return (
<div>
<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