[TIL] onSubmit 동작 안될 때

hanbyul.choi·2023년 6월 27일
0

[TIL]

목록 보기
23/39

GardenGram 이라는 SNS 프로젝트를 진행 중에 데이터를 Post하는 기능을 만들다가 문제를 만났다.

      <PostForm onSubmit={onSubmitGram}>
        <UserInfo>
          <UserImg src={userImg} alt="user_img" />
          <UserName>{name}</UserName>
        </UserInfo>
        <ImgBox>
          <label for="file">
            <BtnUpload>파일 업로드하기</BtnUpload>
          </label>
          <ImgInput ref={fileInput} type="file" id="file" accept="image/*" onChange={onFileChange} />
          {attachment && (
            <PreView>
              <PreViewImg src={attachment} alt="" />
              <RemoveImg onClick={onClearAttachment}>X</RemoveImg>
            </PreView>
          )}
        </ImgBox>
        <TextBox value={contents} placeholder="내용을 입력해주세요." onChange={onTextChange} />
        <Btns>
          <SubmitBtn>게시하기</SubmitBtn>
        </Btns>
      </PostForm>

먼저 위와 같이 render되는 부분을 작성하였고 Form태그를 Styled-Components로 만들었다.

  const onSubmitGram = async (e) => {
   e.preventDefault();
   let attachmentUrl = '';
   if (attachment !== '') {
     const attachmentRef = ref(storage, `${userObj.uid}`);
     await uploadString(attachmentRef, attachment, 'data_url');
     attachmentUrl = await getDownloadURL(ref(storage, attachmentRef));
   }
   const users_img = userObj.img ?? 'default';
   const gramObj = {
     feed_id: `${uid}/${uuidv4()}`,
     name,
     users_img,
     posts_image: attachmentUrl,
     like_count: 0,
     contents,
     time: Date.now()
   };
   await addDoc(collection(db, 'gram'), gramObj);
   setContents('');
   setAttachment('');
   alert('성공적으로 게시되었습니다.');
 };

함수까지 위와 같이 작성했는데 버튼을 클릭해도 아무 동작을 하지 않았다.

처음에는 콘솔창에 뜨는 노란 경고창 때문인 줄 알고 찾아보다가 다시 내코드를 정독해보았다.

이후 문제를 바로 찾을 수 있었다.

const PostForm = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;

  width: 600px;
  height: 750px;
  border: 2px solid #000;
  margin-top: 24px;
  padding: 10px;
`;

styled.div로 Form태그를 만드려 했다.
이러니 onSubmit event가 동작할 수가 없었다.

const PostForm = styled.form`

위와 같이 form으로 변경해주니 정상적으로 작동했다.

대부분 div로 사용하다보니 이런 문제가 발생했던 것 같다.
사용할 수 있는 태그가 따로 있다면 시멘틱하게 작성하는 것이 맞겠다라는 생각이 들었다.

0개의 댓글