|
| 1 | +import React, { Component } from "react"; |
| 2 | +import Form from "react-bootstrap/Form"; |
| 3 | +import Button from "react-bootstrap/Button"; |
| 4 | +import { Card } from "react-bootstrap"; |
| 5 | + |
| 6 | +class Comments extends Component { |
| 7 | + constructor(props) { |
| 8 | + super(props); |
| 9 | + |
| 10 | + this.state = { comments: [], pendingItem: "" }; |
| 11 | + this.onChange = this.onChange.bind(this); |
| 12 | + this.onSubmit = this.onSubmit.bind(this); |
| 13 | + |
| 14 | + console.log(this.state, "state"); |
| 15 | + } |
| 16 | + |
| 17 | + onChange(e) { |
| 18 | + e.preventDefault(); |
| 19 | + console.log(e.target.value); |
| 20 | + |
| 21 | + this.setState({ pendingItem: e.target.value }); |
| 22 | + } |
| 23 | + |
| 24 | + onSubmit(e) { |
| 25 | + e.preventDefault(); |
| 26 | + this.setState({ |
| 27 | + comments: [ |
| 28 | + { |
| 29 | + comment: this.state.pendingItem |
| 30 | + }, |
| 31 | + ...this.state.comments |
| 32 | + ], |
| 33 | + pendingItem: "" |
| 34 | + }); |
| 35 | + } |
| 36 | + deleteComment(index) { |
| 37 | + const newComments = [...this.state.comments] |
| 38 | + newComments.splice(index, 1); |
| 39 | + this.setState({ |
| 40 | + comments: newComments |
| 41 | + }); |
| 42 | + } |
| 43 | + sortComment(){ |
| 44 | + const sortedComments = [...this.state.comments] |
| 45 | + sortedComments.sort((a, b) => ( a.comment > b.comment ) ? 1 : -1) |
| 46 | + this.setState({ |
| 47 | + comments: sortedComments |
| 48 | + }) |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + render() { |
| 53 | + console.log(this.state.comments, "comments at render"); |
| 54 | + return ( |
| 55 | + <div> |
| 56 | + <Form onSubmit={this.onSubmit}> |
| 57 | + <Form.Control |
| 58 | + type="text" |
| 59 | + className="input" |
| 60 | + placeholder="Your Comments Here" |
| 61 | + value={this.state.pendingItem} |
| 62 | + onChange={this.onChange} |
| 63 | + /> |
| 64 | + |
| 65 | + <Button variant="primary" type="submit"> |
| 66 | + Add Your Comments |
| 67 | + </Button> |
| 68 | + |
| 69 | + <Button variant="primary" onClick={()=> { |
| 70 | + this.sortComment() |
| 71 | + }}> |
| 72 | + Sort Comments |
| 73 | + </Button> |
| 74 | + |
| 75 | + </Form> |
| 76 | + <div> |
| 77 | + {this.state.comments.map((comment, index) => { |
| 78 | + return ( |
| 79 | + <Card |
| 80 | + key={index} |
| 81 | + style={{ background: "#31e8e8", opacity: "0.7" }} |
| 82 | + > |
| 83 | + {comment.comment} |
| 84 | + <Button |
| 85 | + onClick={() => { |
| 86 | + this.deleteComment(index); |
| 87 | + }} |
| 88 | + > |
| 89 | + DELETE |
| 90 | + </Button> |
| 91 | + </Card> |
| 92 | + ); |
| 93 | + })} |
| 94 | + </div> |
| 95 | + </div> |
| 96 | + ); |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +export default Comments; |
0 commit comments