Last active
August 3, 2018 15:34
-
-
Save dongcai/c71ebdee342b5a7bb12fd37d52c34a8c to your computer and use it in GitHub Desktop.
Standalone react to render two component with one ReactDOM.render()
This file contains hidden or 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
| const topics = ["php", "jquery", "reactjs"]; | |
| class RedditFeed extends React.Component { | |
| render() { | |
| return ( | |
| <ul> | |
| {this.props.posts.map(post => ( | |
| <li key={post.id}> | |
| <a href={post.url} target="_blank"> | |
| {post.title} | |
| </a> | |
| </li> | |
| ))} | |
| </ul> | |
| ); | |
| } | |
| } | |
| class TopicForm extends React.Component { | |
| constructor(props) { | |
| super(props); | |
| this.state = { | |
| value: "reactjs", | |
| posts: [] | |
| }; | |
| 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({ | |
| ...this.state, | |
| posts | |
| }); | |
| }) | |
| .catch(error => { | |
| console.log(error); | |
| }); | |
| } | |
| handleChange(event) { | |
| this.setState({ value: event.target.value }, () => this.getRedditFeed()); | |
| } | |
| componentDidMount() { | |
| this.getRedditFeed(); | |
| } | |
| render() { | |
| return ( | |
| <div> | |
| <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> | |
| <RedditFeed posts={this.state.posts} /> | |
| </div> | |
| ); | |
| } | |
| } | |
| ReactDOM.render( | |
| React.createElement(TopicForm), | |
| document.getElementById("root") | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment