본문 바로가기
🍀오늘도 삽질 중🍀/React.js

댓글 기능 구현하기

by 매진2 2023. 6. 19.
728x90

바닐라 자바스크립트에서 했던 댓글 기능을 리액트로도 구현해보려고 한다.

DOM 직접 조작과 너무 달라서 한참 애를 먹었다.


멘토님께서 배열을 사용해서 해야한다고 힌트를 줘서 먼저 useState로 변수 선언 먼저 했다.

댓글이 들어가는 input 의 value를 가져오는 idValue,

만들어진 댓글이 들어갈 배열인 saveComment,

댓글이 한글자라도 적히면 버튼의 색을 바꿔줄 btnColor를 만들어주었다.

  const [idValue, setIdValue] = useState('');
  const [saveComment, setSaveComment] = useState([]);
  const [btnColor, setBtnColor] = useState(0.3);

그리고 앞서 포스팅했던 로그인 버튼 활성화랑 같은 내용의 함수를 만들어주고

input과 button 태그에 적용해준다.

  const comment = e => {
    setIdValue(e.target.value);
  };

  const changeBtnColor = () => {
    setBtnColor(!btnColor);
  };

               <form className="enterComment">
              <input
                id="input"
                placeholder="댓글 달기..."
                value={idValue}
                onChange={e => {
                  comment(e);
                }}
              />
              <button
                id="button"
                style={{ opacity: `${idValue > '0' ? 1 : 0.3}` }}
                disabled={idValue > '0' ? false : true}
                onChange={changeBtnColor}
                onClick={post}
              >
                게시
              </button>
            </form>

중요한 부분은 지금부터다!

Post 라는 함수를 만들어주고 매개변수에 e를 넣어주었다.

saveComment라는 배열에 전개연산자를 이용해 배열의 요소를 나열해주는 postSaveComment를 변수로 선언한다.

그리고 input의 Value를 postSaveComment에 넣어주고 set 함수로 실행시켜준다.

실행 후에는 초기값인 빈 따옴표로 돌려준다.

  const post = e => {
    const postSaveComment = [...saveComment];
    postSaveComment.push(idValue);
    setSaveComment(postSaveComment);
    setIdValue('');
  };

댓글이 들어갈 수 있는 공간인 newComment div태그를 만들어주고

saveComment에 map 함수를 돌려준다.

return 값으로는 html을 넣어주고 ele=input value, idx는 배열의 인덱스 값으로 넣어준다.

<div id="newComment">
 {saveComment.map((ele, idx) => {
 return <p key={idx}>wecode {ele}</p>;
 })}
</div>

완성된 화면은 이러하다.

 

아래는 전체 코드이며 댓글과 관련없는 html 태그들은 지웠다.

function Main() {
  const [idValue, setIdValue] = useState('');
  const [saveComment, setSaveComment] = useState([]);
  const [btnColor, setBtnColor] = useState(0.3);

  const comment = e => {
    setIdValue(e.target.value);
  };

  const changeBtnColor = () => {
    setBtnColor(!btnColor);
  };

  const post = e => {
    const postSaveComment = [...saveComment];
    postSaveComment.push(idValue);
    setSaveComment(postSaveComment);
    setIdValue('');
  };


  return (
              <div id="newComment">
                {saveComment.map((ele, idx) => {
                  return <p key={idx}>wecode {ele}</p>;
                })}
              </div>
            <form className="enterComment">
              <input
                id="input"
                placeholder="댓글 달기..."
                value={idValue}
                onChange={e => {
                  comment(e);
                }}
              />
              <button
                id="button"
                style={{ opacity: `${idValue > '0' ? 1 : 0.3}` }}
                disabled={idValue > '0' ? false : true}
                onChange={changeBtnColor}
                onClick={post}
              >
                게시
              </button>
            </form>
  );
}
728x90