본문으로 건너뛰기
poylog

개발·AI

댓글 입력 오류

2분

codelike 댓글이 중복 표시된 Justgram 게시물 댓글 영역

댓글을 받으면서 공백인 상태에서도 댓글 입력이 들어가는 문제가 있었다. 처음엔 button에 집중해서 문제를 해결했지만 form에서 해결하는 방법이 더 만족스러웠다.

button에서 onClick

javascript
        <form>
          <input
            ref={value}
            onChange={onChange}
            placeholder="댓글 달기..."
          />
          <button
            onClick={post}
            style={{
              opacity: isValid ? 0.1 : 1
            }}
          >
            게시
          </button>
        </form>

form 태그 안에서 input과 button이 있고, button에 onClick으로 클릭 시 input 값을 댓글로 쓰도록 만들었다. 

javascript
  const [userName] = useState('codelike');
  const [commmentArr, setCommentArr] = useState([]);
  const [isValid, setIsValid] = useState(true);
  const [id, setId] = useState(0);
  const value = useRef();

  const post = e => {
    e.preventDefault();
    if (!isValid && e.target.form[0].value.length>0) {
      setId(id + 1);
      let newComment = {
        id: id,
        content: value.current.value,
      };
      setCommentArr([...commmentArr, newComment]);
    }
    e.target.form[0].value = "";
    setIsValid(true)
  }

  const onChange = (e) => {
    e.target.value.length > 0
      ? setIsValid(false)
      : setIsValid(true)
  }

button으로 input의 정보가 넘어오기 때문에 댓글을 넘겨주고 input 창을 비우려면 button으로 넘어온 데이터중 input부분을 찾아내 빈칸으로 만들어 주어야 했다.

javascript
e.target.form[0].value = "";

input 창의 변화를 감지하면 바로 '게시' 버튼의 불투명도를 조절하게 만들었고, input 창을 비운 후에 IsValid를 false로 바꿔주고 끝나기 때문에 다시 게시 버튼의 opacity를 낮춰준다.

결과적으로 댓글을 넘겨줌은 물론이고

  • input의 입력 유무에 따른 버튼 활/비활성화
  • 댓글 제출 후 input칸 비우기
  • 비운 후에 버튼 비활성화 시키기

이런 내용들을 지킬 수 있었지만, input을 비울 때 사용한 부분처럼 언뜻 보면 어디를 지칭하는 부분인지 모르겠고, if문의 조건도 마음에 들지 않았다. 그래서 onSubmit을 써보게 되었다.

form에서 onSubmit

javascript
<form onSubmit={onSubmit}>
  <input
    ref={ref}
    onChange={onChange}
    placeholder="댓글 달기..."
  />
  <button
    style={{
      opacity: isValid ? 0.5 : 1
    }}
  >
    게시
  </button>
</form>

button의 onClick을 없애고 form 태그에 onSubmit을 주었다. 이렇게 바꾸면서 앞전의 방식대로 사용할 때 useRef() 훅을 사용해놓고 적극적으로 쓰지 않았던 부분도 반영했다.

javascript
const [userName] = useState('codelike');
  const [commmentArr, setCommentArr] = useState([]);
  const [isValid, setIsValid] = useState(true);
  const [id, setId] = useState(0);
  const ref = useRef();

  const onSubmit = e => {
    e.preventDefault();
    if (ref.current.value.length > 0) {
      setId(id+1);
      let newComment = {
        id: id,
        content: ref.current.value,
      };
      setCommentArr([...commmentArr, newComment]);
      ref.current.value = "";
      setIsValid(true);
    }
  }

  const onChange = () => {
    ref.current.value.length > 0
      ? setIsValid(false)
      : setIsValid(true)
  };

댓글에 영향을 주는 내용은 일맥상통하나, if문의 조건을 조금 더 직관적으로 바꿀 수 있었고,

javascript
ref.current.value = "";

useRef() 훅을 사용했기 때문에 이 부분이 input의 내용을 지운다는 내용임을 알 수 있게 했다.

form 안에 있는 button이 제출 역할을 해주니 거기서 모든 것을 해결하려 초점을 맞췄다가 많이 돌아온 기분이 든다. 처음부터 form에서 조작하거나, form 없이 input, button 만 사용하던지 했으면 하는 아쉬움이 있다.

요약

  1. form에 넣었으면 form으로 관리하자
  2. useRef() 넣었으면 적재적소에 효율적으로 사용하자
  3. 어쨌든 button에서 타고 가면 input값을 찾을 수는 있다.