React를 이용한 댓글창 기능 활성화

HYUK·2023년 1월 30일
0

react

목록 보기
8/15

사용자가 댓글 입력후 댓글 입력 버튼 클릭시 댓글이 추가되도록 구현해 보았다. 이 과정에 있어서 state로 저장한 댓글을 배열과 map메서드를 이용하여 구현해 보았다.

const Comment = () => {
  const [comment, setComment] = useState('');
  const hendleComment = event => {
    setComment(event.target.value);
  };
  
  ...중간생략...
  
  <input
    className="writeMention"
    type="text"
    placeholder="댓글 달기..."
    value={comment}
    onChange={hendleComment}
    />
  

먼저 입력된 댓글들을 state에 담아주기 위해 input태그에 onChange 이벤트를 걸어주었다.

const [comment, setComment] = useState('');
  const hendleComment = event => {
    setComment(event.target.value);
  };

const [commentArray, setCommentArray] = useState([]);
  const eventComment = () => {
    const result = [...commentArray];
    result.push(comment);
    setCommentArray(result);
    setComment('');
  };

const changeColor = comment.length > 0;

...중간생략...

<ul className="comment-ul">
    {commentArray.map(function (a, i) {
     return <Newcomment key={i} comment={a} />;
    })}
</ul>

...중간생략...

<input
  className={changeColor ? 'changeColorBtn' : 'writeBtn'}
  type="button"
  value="게시"
  onClick={eventComment}
 />
  1. 입력된 댓글들이 배열에 저장될 수 있는 state를 만들어준다.
  2. eventComment 함수에 commentArray값을 spread를 이용하여 이후에 들어오는 댓글값들까지 계속해서 한 배열에 들어가도록 만들어준다.
  3. commentArray값을 받은 result 변수에 push를 이용하여 comment값을 push 해준다.
  4. setCommentArray에 result값을 적용한다.
  5. input창을 다시 처음으로 비워주기위해 setComment값을 빈스트링으로 초기화 시켜준다.
//comment.js

const [comment, setComment] = useState('');
  const hendleComment = event => {
    setComment(event.target.value);
  };
  const [commentArray, setCommentArray] = useState([]);
  const eventComment = () => {
    const result = [...commentArray];
    result.push(comment);
    setCommentArray(result);
    console.log(result);
    setComment('');
    console.log(setComment(''));
  };

...중간생략....

<ul className="comment-ul">
        {commentArray.map(function (a, i) {
          return <Newcomment key={i} comment={a} />;
        })}
</ul>
// Newcomment.js

import React from 'react';

const Newcomment = props => {
  return <p>{props.comment}</p>;
};

export default Newcomment;
  1. comment.js에서 eventComment 함수를 통해서 입력된 댓글들을 배열로 저장하고 그 배열을 map 메서드를 이용하여 입력된 댓글 배열들을 한번씩 반복하면서 모든 댓글 내용들을 다시 출력하고 있다.
  2. Newcomment.js에서 props를 통해서 넘겨준걸 comment.js의 map메서드 요소부분인 comment={a} 부분에서 데이터를 받아 출력
profile
step by step

0개의 댓글