comments.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. /*
  2. Good practices:
  3. - name CSS classNamees like the associated component
  4. - prefix non-React method names by an "_"
  5. - pass a "key" attribute to elements in a loop
  6. State
  7. - direct reads, write through setState()
  8. - declare initial state in constructor()
  9. - setState() calls render(): beware loops = avoid it in render()
  10. Refs:
  11. - are called by React during render()
  12. - (foo) => { this._bar = foo; ) translates to function(foo) { this._bar = foo; }.bind(this);
  13. Events:
  14. - React events are "synthetic" events, masking the browser behaviour differences
  15. - https://facebook.github.io/react/docs/events.html
  16. Lifecycle methods:
  17. - Main: componentWillMount / componentDidMount / componentWillUnmount
  18. - fetch initial data from cWM, start a refresh poll loop from cDM, stop loop from cWU
  19. - https://facebook.github.io/react/docs/react-component.html
  20. JSX:
  21. - "className", not "class"
  22. - knows how to render an array of JSX elements, not just one.
  23. */
  24. class Comment extends React.Component {
  25. render() {
  26. return (
  27. <div className="comment">
  28. <p className="comment-header">{this.props.author}</p>
  29. <p className="comment-body">
  30. {this.props.body}
  31. </p>
  32. <div className="comment-footer">
  33. <a href="#" className="comment-footer-delete">
  34. Delete comment
  35. </a>
  36. </div>
  37. </div>
  38. );
  39. }
  40. }
  41. class CommentForm extends React.Component {
  42. _handleSubmit(event) {
  43. // Prevent the page from reloading.
  44. event.preventDefault();
  45. // this._author/this._body are populated by refs in JSX
  46. let author = this._author;
  47. let body = this._body;
  48. // Since they are elements, we need to take their ".value".
  49. this.props.addComment(author.value, body.value);
  50. // addComment is called on this.props, meaning it is passed by component parent.
  51. }
  52. render() {
  53. return (
  54. <form className="comment-form" onSubmit={this._handleSubmit.bind(this)}>
  55. <label>Join the discussion</label>
  56. <div className="comment-form-fields">
  57. <input placeholder="Name:"
  58. ref={(input) => { this._author = input; } } /* "this" is CommentForm... *//>
  59. <textarea placeholder="Comment:"
  60. ref={(textarea) => { this._body = textarea; /* ...because of lexical scope */ } } />
  61. </div>
  62. <div className="comment-form-actions">
  63. <button type="submit">Post comment</button>
  64. </div>
  65. </form>
  66. );
  67. }
  68. }
  69. class CommentBox extends React.Component {
  70. constructor() {
  71. super();
  72. this.state = {
  73. showComments: false,
  74. comments: []
  75. };
  76. }
  77. _addComment(author, body) {
  78. const comment = {
  79. id: this.state.comments.length + 1,
  80. author,
  81. body
  82. };
  83. // concat(), not push(): push() mutates the data, concat doesn't.
  84. // By allocating a new reference, for comments, React detects the change fast.
  85. this.setState({comments: this.state.comments.concat([comment])});
  86. }
  87. _fetchComments() {
  88. jQuery.ajax({
  89. method: "GET",
  90. url: "/static/comments.json",
  91. // Arrow function: keep "this" binding to the class instance.
  92. success: (comments) => {
  93. this.setState({comments});
  94. }
  95. });
  96. }
  97. _getComments() {
  98. return this.state.comments.map((comment) => {
  99. return (<Comment
  100. author={comment.author}
  101. body={comment.body}
  102. key={comment.id} />);
  103. });
  104. }
  105. _getCommentsTitle(commentCount) {
  106. if (commentCount === 0) {
  107. return "No comments yet";
  108. } else if (commentCount === 1) {
  109. return "1 comment";
  110. }
  111. return `${commentCount} comments`;
  112. }
  113. _handleClick() {
  114. this.setState({
  115. showComments: !this.state.showComments
  116. });
  117. }
  118. componentDidMount() {
  119. this._timer = setInterval(() => this._fetchComments(), 5000);
  120. }
  121. componentWillMount() {
  122. this._fetchComments();
  123. }
  124. componentWillUnmount() {
  125. clearInterval(this._timer);
  126. }
  127. render() {
  128. const comments = this._getComments();
  129. let buttonText = "Show comments";
  130. let commentNodes;
  131. if (this.state.showComments) {
  132. commentNodes = <div className="comment-list">{comments}</div>;
  133. buttonText = "Hide comments";
  134. }
  135. return (
  136. <div className="comment-box">
  137. <button onClick={this._handleClick.bind(this)}>{buttonText}</button>
  138. <h4 className="comment-count">{this._getCommentsTitle(comments.length)}</h4>
  139. <CommentForm addComment={this._addComment.bind(this)} />
  140. {commentNodes}
  141. </div>
  142. );
  143. }
  144. }
  145. ReactDOM.render(
  146. <CommentBox />, document.getElementById('comments-app')
  147. );