SHOW COMMENTS

 HERE, WE TRY TO DISPLAY ALL THE COMPONENTS.

ONCE A FORM IS SUBMITTED, IT SHOULD BE DISPLAYED. TO DO THIS, WE SHOULD FOLLOW REACT HIERARCHY SO THAT A COMPONENT CAN BE IMPORTED.

BUT HERE, IF WE TRY TO IMPORT COMMENT FORM'S FUNCTION FORM COMMENTFORM COMPONENT, ONLY THE MOST RECENT COMMENT IS DISPLAYED.

SO,WE IMPORT FUNCTION FROM COMMENTS INTO COMMENTFORM.

COMMENTS.JSX

import { useState } from "react";
import "./Comments.css";
import CommentForm from "./CommentsForm";
export default function Comments() {
  let [comments, setComments] = useState([
    {
      username: "@abhi",
      remarks: "nice work",
      rating: "4",
    },
  ]);

  let addComment = (comment) => {
    setComments((currComments) => [...currComments, comment]);
 
  };
  return (
    <>
      <div>
        <h2>All Comments!!</h2>
        {comments.map((comment, idx) => (
          <div className="Comments" key={idx}>
            <p>{comment.remarks}</p>
            <p>rating:{comment.rating}</p>
            <p>-{comment.username}</p>
          </div>
        ))}
      </div>
      <CommentForm addComment={addComment} />
    </>
  );
}

COMMENTFORM.JSX

import { useState } from "react";

export default function CommentForm({ addComment }) {
  let [commentForm, setCommentForm] = useState({
    username: "",
    remarks: "",
    rating: "",
  });

  let handleInputChange = (event) => {
    setCommentForm((currData) => {
      return { ...currData, [event.target.name]: event.target.value };
    });
  };
  let handleSubmit = (event) => {
    event.preventDefault();
    console.log(commentForm);
    addComment(commentForm);
    setCommentForm({
      username: "",
      remarks: "",
      rating: 5,
    });
  };
  return (
    <form onSubmit={handleSubmit}>
      <h2>Comment Form</h2>
      <label htmlFor="username">Username:&nbsp;</label>
      <input
        placeholder="Enter username"
        type="text"
        value={commentForm.username}
        id="username"
        onChange={handleInputChange}
        name="username"
      />
      <br />
      <br />

      <label htmlFor="remarks">Remarks:&nbsp;</label>
      <input
        placeholder="Write remarks"
        type="text"
        value={commentForm.remarks}
        id="remarks"
        onChange={handleInputChange}
        name="remarks"
      />
      <br />
      <br />

      <label htmlFor="rating">Rating:&nbsp;</label>
      <input
        type="number"
        value={commentForm.rating}
        id="rating"
        onChange={handleInputChange}
        name="rating"
        min={1}
        max={5}
      />
      <br />

      <button>submit</button>
    </form>
  );
}


COMMENTS.CSS

.Comments{
    border: 1px solid yellow;
    border-radius: 15px;
    padding: 10px;
    width: 250px;
    margin-top: 10px;
}






Comments

Popular posts from this blog

DEPENDENCIES IN useEffect()

ACTIVITY1

CONDITIONALS