Mission 3) Main | 댓글 기능(State & Event)

이해용·2022년 5월 16일
0
post-thumbnail

Mission 3) Main | 댓글 기능

  1. 사용자가 댓글 입력 후 enter 를 누르거나 왼쪽의 버튼 클릭 시 댓글이 추가되도록 구현해주세요.
  2. 댓글 기능을 구현하기 위해서는 배열 데이터 타입을 활용해야 합니다.
  3. Array.map 참고해서 시도해주세요.

댓글 구현

예상 흐름
댓글 input value 저장 -> 댓글 입력 값 저장 공간 지정 -> 댓글 출력

댓글 input value 저장

  1. state 값을 먼저 선언한다.
    const [comment, setComment] = useState('');

  2. commentInput 함수를 setComment에 저장될 수 있도록 선언한다.
    const commentInput = event => setComment(event.target.value);

  3. 댓글 input 값에 comment의 값을 넣을 수 있도록 input 안에 value 속성을 설정해준다.

  4. onChange 이벤트를 실행시키기 위해 commentInput 함수를 넣어준다.
    <input type="text" placeholder="댓글 달기..." value={comment} onChange={commentInput} />

댓글 입력 값 저장 공간 지정

  1. 배열이 저장될 수 있도록 state 값을 빈배열로 선언한다.
    const [commentArray, setCommentArray] = useState([])
  2. 입력한 댓글이 등록될 수 있돌고 registComment의 이름으로 함수를 선언하고 이 함수 안에서 입력된 comment 값이 배열로 출력될 수 있도록 지정해준다. 또한, 아무 입력이 없다면 전송되지 않도록 설정해준다.
const registerComment = event => {
  event.preventDefault(); // react에서 다른 이벤트가 발생되지 않도록 해주는 명령어
  if (comment === '') {
    return; // 만일 comment에 아무 값도 없다면 바로 return 된다.
  }
  setCommentArray(commentValueList => [...commentValueList, comment]); 
  // comment의 값이 새로 입력된다면 commentValueList에 새로운 배열인 ...commentValueList가 입력되며 이 값은 setCommentArray에 전송된다.
  setComment(''); // setCommentArray에 값이 입력되면 input값엔 아무 값도 없게 초기화 된다.
}

event.preventDefault();란?

  1. 함수 registerComment를 form 태그의 onSubmit 이벤트를 사용하여 값을 넣어준다.

    <form id="comment" onSubmit={registComment}>

    form 태그에 자동으로 enter를 치면 전송될 수 있도록 하는 기능이 있어 댓글에는 form 태그를 이용한다고 한다.

  2. enter key 뿐 아니라 게시 button 도 클릭하면 전송이 될 수 있도록 onClick 이벤트를 사용하여 registComment 함수를 넣어준다.

    <button type="button" onClick={registComment}

댓글 출력

  1. map method를 이용하여 value 값이 입력되면 commentArray 배열 안에 저장될 수 있게 하여 ul tag 안의 li tag 가 출력될 수 있도록 설정해준다.
<ul className="todo-list">
  {commentArray.map((value, index) => (
    <li key={index}>
      <span>Hey.yong44</span>
      <span>{value}</span>
      <Button>x</Button>
    </li>
    ))}
</ul>

기타 구현한 사항

  1. comment 에 값이 1개라도 입력되면 게시 button 의 색이 변경될 수 있도록 값을 지정해주었다.
const commentValid = comment.length >= 1;

return (
	...
  <button type="button" onClick={registComment} className={commentValid ? 'buttonEnabled' : 'buttonDisabled'}>
	...
    )

최종 결과

function MainHaeYongLee() {
  const [comment, setComment] = useState('');
  const commentInput = event => setComment(event.target.value);

  const [commentArray, setCommentArray] = useState([]);
  const registComment = event => {
    event.preventDefault();
    if (comment === '') {
      return;
    }
    setCommentArray(commentValueList => [...commentValueList, comment]);
    setComment('');
  };

  const commentValid = comment.length >= 1;
  
  return (  
    ...
	<ul className="todo-list">
		{commentArray.map((value, index) => (
			<li key={index}>
				<span>Hey.yong44</span>
                <span>{value}</span>
                <button>x</button>
            </li>
		))}
	</ul>
    ...
	<form id="comment" onSubmit={registComment}>
		<i className="fa-regular fa-face-smile fa-lg" />
			<input
			type="text"
				placeholder="댓글 달기..."
				value={comment}
				onChange={commentInput}
			/>
			<button
				type="button"
				onClick={registComment}
				className={
				commentValid ? 'buttonEnabled' : 'buttonDisabled'
				}
			>
				게시
			</button>
	</form>
    ...
}

참고 및 출처
위코드 강의
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://velog.io/@cullen/React-Westagram-%EB%8C%93%EA%B8%80-%EC%B6%94%EA%B0%80-%ED%95%A8%EC%88%98
https://velog.io/@moolbum/React-%EC%9D%B8%EC%8A%A4%ED%83%80%EA%B7%B8%EB%9E%A8-%EB%8C%93%EA%B8%80
https://developer.mozilla.org/ko/docs/Web/API/Event/preventDefault

profile
프론트엔드 개발자입니다.

0개의 댓글