Skip to content

Instantly share code, notes, and snippets.

@JosephRedfern
Created January 10, 2017 11:51
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 JosephRedfern/407a1822c8cbca4b546ae21656bafdf4 to your computer and use it in GitHub Desktop.
Save JosephRedfern/407a1822c8cbca4b546ae21656bafdf4 to your computer and use it in GitHub Desktop.
Reactddit
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class Listing extends Component {
constructor(params){
super(params);
this.title = params.title;
this.ups = params.ups;
}
render(){
return (
<div>[{this.ups}] {this.title}</div>
);
}
}
class App extends Component {
constructor(props){
super(props);
this.state = {entries : [], loading: true, subreddit:this.props.params.subreddit};
this.updatePosts = this.updatePosts.bind(this);
this.fetchPosts = this.fetchPosts.bind(this);
this.fetchPosts();
}
fetchPosts() {
this.setState({loading: true});
alert(this.state.subreddit);
fetch("https://www.reddit.com/r/"+this.state.subreddit+".json")
.then((response) => {
return response.json()
})
.then((json) => this.updatePosts(json));
}
updatePosts = (json) => {
var entries = [];
for(var entry of json["data"]["children"]){
var title = entry["data"]["title"];
var ups = entry["data"]["ups"];
var k = entry["data"]["id"];
entries.push((<Listing key={k} ups={ups} title={title} />));
}
console.log("Setting state...");
this.setState({listings: entries, loading: false});
}
render() {
return (
<div className="App">
<div className="App-header">
<img style={{animation: this.state.loading ? 'App-logo-spin infinite 1s linear' : 'none'}} src={logo} className="App-logo" alt="logo" />
<h1>Welcome to Reactditt</h1>
<h2>Subreddit: {this.state.subreddit}</h2>
<input type="text" onChange={(ev) => {this.setState({subreddit: ev.target.value})}} />
<button onClick={() => this.fetchPosts()}>Refresh</button>
</div>
<div>
{this.state.listings}
</div>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment