// import { useEffect } from "react";
import { useState } from "react";
const Comment = () => {
const [userInput, setUserInput] = useState({
nickname: "",
comment: "",
});
const [commentArr, setCommentArr] = useState([]);
const { nickname, comment } = userInput;
const onChange = (e) => {
e.preventDefault();
const { value, name } = e.target;
setUserInput({
...userInput,
[name]: value,
});
};
const submit = (e) => {
e.preventDefault();
setUserInput({ nickname, comment });
const newComment = [...commentArr];
newComment.push(userInput);
setCommentArr(newComment);
setUserInput({
nickname: "",
comment: "",
});
};
return (
<div>
<div>
<h2>Comment List</h2>
<ul>
{commentArr.map(({ nickname, comment }) => {
return (
<CommentList
nickname={`ID : ${nickname}`}
comment={`댓글 : ${comment}`}
key={nickname.length}
/>
);
})}
<CommentList />
</ul>
</div>
<h4>댓글을 입력해보세요</h4>
<form onSubmit={submit}>
<input
name="nickname"
value={nickname}
onChange={onChange}
placeholder="ID"
type="text"
/>
<input
name="comment"
value={comment}
onChange={onChange}
placeholder="Comment..."
type="text"
/>
<button>입력</button>
</form>
</div>
);
};
const CommentList = ({ nickname, comment }) => {
return (
<li>
<span>
<b>{nickname}</b>
</span>
<br></br>
<span>{comment}</span>
</li>
);
};
export default Comment;
'⚛️ React' 카테고리의 다른 글
useParams와 useLocation을 이용한 페이지 이동 (2) (0) | 2022.06.05 |
---|---|
useParams와 useLocation을 이용한 페이지 이동 (1) (0) | 2022.06.05 |
import order convention (0) | 2022.05.29 |
input과 type으로 알아보는 useState ⚛️ (0) | 2022.05.21 |
[TIL] React Intro (0) | 2022.05.09 |
댓글