Skip to content

Instantly share code, notes, and snippets.

@dongcai
Created August 1, 2018 18:36
Show Gist options
  • Save dongcai/21fab10f681ba46896561398cd835578 to your computer and use it in GitHub Desktop.
Save dongcai/21fab10f681ba46896561398cd835578 to your computer and use it in GitHub Desktop.
Every request only updates the data source, and the ReactJS does the rest
const topics = ["php", "jquery", "reactjs"];
class RedditFeed extends React.Component {
render() {
return (
<div>
<ul>
{this.props.posts.map(post => (
<li key={post.id}>
<a href={post.url} target="_blank">
{post.title}
</a>
</li>
))}
</ul>
</div>
);
}
}
class TopicForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: "reactjs" };
this.handleChange = this.handleChange.bind(this);
}
getRedditFeed() {
console.log(this.state.value);
axios
.get(`https://www.reddit.com/r/${this.state.value}.json`)
.then(res => {
const posts = res.data.data.children.map(obj => obj.data);
// this.setState({ posts });
ReactDOM.render(
React.createElement(RedditFeed, { posts }),
document.getElementById("root")
);
})
.catch(error => {
console.log(error);
});
}
handleChange(event) {
this.setState({ value: event.target.value }, () => this.getRedditFeed());
}
componentDidMount() {
this.getRedditFeed();
}
render() {
return (
<form>
<div className="form-group">
<label>
Pick your favorite topic:
<select
className="form-control"
value={this.state.value}
onChange={this.handleChange}
>
{topics.map(topic => <option value={topic}>{topic}</option>)}
</select>
</label>
</div>
</form>
);
}
}
ReactDOM.render(
React.createElement(TopicForm),
document.getElementById("topic")
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment