App.jsx 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // App component : represents the whole app.
  2. App = React.createClass({
  3. // This mixin makes the getMeteorData work.
  4. mixins: [ReactMeteorData],
  5. getInitialState() {
  6. return {
  7. hideCompleted: false
  8. };
  9. },
  10. // Loads items from the Tasks collection and puts them on this.data.tasks.
  11. getMeteorData() {
  12. let query = {};
  13. const uncheckedQuery = { checked: { $ne: true} };
  14. if (this.state.hideCompleted) {
  15. // If hideCompleted is checked, filter tasks.
  16. query = uncheckedQuery;
  17. }
  18. let result = {
  19. tasks: Tasks.find(query, { sort: { createdAt: -1 }}).fetch(),
  20. // Since we already have the data in the client-side Minimongo collection,
  21. // adding this extra count doesn't involve asking the server for anything.
  22. incompleteCount: Tasks.find(uncheckedQuery).count(),
  23. currentUser: Meteor.user()
  24. };
  25. // Meteor._debug("result", result);
  26. return result;
  27. },
  28. renderTasks() {
  29. return this.data.tasks.map((task) => {
  30. // Meteor._debug(task._id);
  31. return <Task key={task._id} task={task} />;
  32. });
  33. },
  34. handleSubmit(event) {
  35. event.preventDefault();
  36. // Meteor._debug('refs', this.refs);
  37. // Find the text field via the React ref.
  38. var text = ReactDOM.findDOMNode(this.refs.textInput).value.trim();
  39. Tasks.insert({
  40. text: text,
  41. createdAt: new Date(), // Current time
  42. owner: Meteor.userId(), // _id of logged-in user
  43. username: Meteor.user().username // username of logged-in user
  44. });
  45. // Clear form to allow a new input.
  46. ReactDOM.findDOMNode(this.refs.textInput).value = '';
  47. },
  48. toggleHideCompleted() {
  49. this.setState({
  50. hideCompleted: !this.state.hideCompleted
  51. });
  52. },
  53. render() {
  54. return (
  55. <div className="container">
  56. <header>
  57. <h1>Todo list ({this.data.incompleteCount})</h1>
  58. <label className="hide-completed">
  59. <input type="checkbox" readOnly={true}
  60. checked={this.state.hideCompleted}
  61. onClick={this.toggleHideCompleted} />
  62. Hide completed
  63. </label>
  64. <AccountsUIWrapper />
  65. {/* These are JSX comments. */}
  66. { this.data.currentUser ?
  67. // Beware: for React, onsubmit is not the same as onSubmit, the former doesn't work.
  68. <form className="new-task" onSubmit={this.handleSubmit} >
  69. <input type="text" ref="textInput" placeholder="Type to add new tasks" />
  70. </form> : ''
  71. }
  72. </header>
  73. <ul>
  74. {this.renderTasks()}
  75. </ul>
  76. </div>
  77. );
  78. }
  79. });