Skip to content

Instantly share code, notes, and snippets.

@aerrity
Created December 13, 2018 17:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aerrity/7538a221865525dd4872e134bc11dcbf to your computer and use it in GitHub Desktop.
Save aerrity/7538a221865525dd4872e134bc11dcbf to your computer and use it in GitHub Desktop.
Solution to Comment Activity
import React from "react";
class Comment extends React.Component {
constructor(props) {
super(props);
// Setup the state data
this.state = {
flagged: false
};
// This binding is necessary to make `this` work in the onclick callback
this.handleClick = this.handleClick.bind(this);
}
// Event handler for the button
handleClick() {
// When clicked flip between flagged/not flagged
this.setState(prevState => ({
flagged: !prevState.flagged
}));
}
// Define what happens when this component gets drawn on the UI
// Note the two instances of conditional rendering { ___ ? ___ : ____ }
render() {
return (
<div className="column is-half is-offset-one-quarter">
<div
className={
this.state.flagged
? "card notification is-danger"
: "card notification is-primary"
}
>
<div className="card-content">
<div className="media">
<div className="media-content">
<p className="title is-4">{this.props.name}</p>
<p className="subtitle is-6">{this.props.email}</p>
<p className="subtitle">{this.props.body}</p>
<button type="button" onClick={this.handleClick}>
{this.state.flagged
? "Flag as appropriate"
: "Flag as inappropriate"}
</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
// Allow this to be imported by another JS file
export default Comment;
import React from "react";
import ReactDOM from "react-dom";
import Comment from "./Comment";
// Note: ensure you've installed axios with 'npm install axios'
import axios from "axios";
class CommentList extends React.Component {
constructor(props) {
super(props);
// this is where we will store the comments, when they have been retrieved
this.state = { comments: [] };
}
// Runs when component is mounted
componentDidMount() {
// Get data for 500 comments
axios
.get("https://jsonplaceholder.typicode.com/comments/")
.then(response => {
// GET request was successful, store the comments in state
this.setState({ comments: response.data });
})
.catch(err => {
// GET failed, log the error
console.log(err);
});
}
render() {
// For each comment, generate a Comment component and pass data in as props
const commentList = this.state.comments.map(item => (
<Comment
key={item.id}
name={item.name}
email={item.email}
body={item.body}
/>
));
return <div className="columns is-multiline">{commentList}</div>;
}
}
ReactDOM.render(<CommentList />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment