Created
January 10, 2017 11:51
-
-
Save JosephRedfern/407a1822c8cbca4b546ae21656bafdf4 to your computer and use it in GitHub Desktop.
Reactddit
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, { 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