Explorar o código

L2.8 dynamic parameters.

Frederic G. MARAND %!s(int64=8) %!d(string=hai) anos
pai
achega
0e0e37a02d
Modificáronse 1 ficheiros con 37 adicións e 6 borrados
  1. 37 6
      src/comments.js

+ 37 - 6
src/comments.js

@@ -1,4 +1,18 @@
-// Good practice: name CSS classNamees like the associated component
+/*
+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
+
+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() {
@@ -19,16 +33,33 @@ class Comment extends React.Component {
 }
 
 class CommentBox extends React.Component {
+  _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`;
+  }
+
   render() {
+    const comments = this._getComments();
     return (
       <div className="comment-box">
         <h3>Comments</h3>
-        <h4 className="comment-count">2 comments</h4>
+        <h4 className="comment-count">{this._getCommentsTitle(comments.length)}</h4>
         <div className="comment-list">
-          <Comment
-            author="Morgan McCircuit" body="Great picture!" />
-          <Comment
-            author="Bending Bender" body="Excellent stuff!" />
+          {comments}
         </div>
       </div>
     );