1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- /*
- Good practices:
- - name CSS classNamees like the associated component
- - prefix non-React method names by an "_"
- - pass a "key" attribute to elements in a loop
- State
- - direct reads, write through setState()
- - declare initial state in constructo()
- JSX:
- - "className", not "class"
- - knows how to render an array of JSX elements, not just one.
- */
- const commentList = [
- { id: 1, author: "Morgan McCircuit", body: "great picture!" },
- { id: 2, author: "Bending Bender", body: "Excellent stuff" }
- ];
- class Comment extends React.Component {
- render() {
- return (
- <div className="comment">
- <p className="comment-header">{this.props.author}</p>
- <p className="comment-body">
- {this.props.body}
- </p>
- <div className="comment-footer">
- <a href="#" className="comment-footer-delete">
- Delete comment
- </a>
- </div>
- </div>
- );
- }
- }
- class CommentBox extends React.Component {
- constructor() {
- super();
- this.state = {
- showComments: false
- };
- }
- _getComments() {
- return commentList.map((comment) => {
- return (<Comment
- author={comment.author}
- body={comment.body}
- key={comment.id} />);
- });
- }
- _getCommentsTitle(commentCount) {
- if (commentCount === 0) {
- return "No comments yet";
- } else if (commentCount === 1) {
- return "1 comment";
- }
- return `${commentCount} comments`;
- }
- _handleClick() {
- this.setState({
- showComments: !this.state.showComments
- });
- }
- render() {
- const comments = this._getComments();
- let buttonText = "Show comments";
- let commentNodes;
- if (this.state.showComments) {
- commentNodes = <div className="comment-list">{comments}</div>;
- buttonText = "Hide comments";
- }
- return (
- <div className="comment-box">
- <button onClick={this._handleClick.bind(this)}>{buttonText}</button>
- <h4 className="comment-count">{this._getCommentsTitle(comments.length)}</h4>
- {commentNodes}
- </div>
- );
- }
- }
- ReactDOM.render(
- <CommentBox />, document.getElementById('comments-app')
- );
|