24.11.30

강연주·2024년 11월 30일

📚 TIL

목록 보기
105/186

🖥️ MeetupForm.tsx

...

  const startedAtRef = useRef<HTMLInputElement>(null);
  const [isStartedAtNull, setIsStartedAtNull] = useState(false);

...


if (!startedAtRef.current) {
      console.error("startedAtRef가 인풋에 연걸 안돼있어");
      return;
    }
    const startedAt = isStartedAtNull ? null : startedAtRef.current;
    console.log("Submitted startedAt:", startedAt);
    
    ...

    const newMeetup: Meetup = {
      name: nameRef.current?.value || "",
      description: descriptionRef.current?.value || "",
      place: placeRef.current?.value || "",
      placeDescription: placeDescriptionRef.current?.value || "",
      startedAt: isStartedAtNull ? null : startedAtRef.current,
      endedAt: endedAtRef.current?.value || "",
      adTitle: adTitleRef.current?.value || "",
      adEndedAt: adEndedAtRef.current?.value || "",
      isPublic: isPublicRef.current?.checked || true, // `checked`로 값 가져오기
      image: imageRef.current?.value || "",
      category: categoryRef.current?.value || "",
    };
    
 ...
 
 <LabeledInput id="startedAt" name="startedAt" label="모임 시작 날짜" type="date"
 ref={startedAtRef} disabled={isStartedAtNull} required />
 
            <LabeledInput
              id="미정"
              name="미정"
              label="미정"
              type="checkbox"
              onChange={event => {
                setIsStartedAtNull(event.target.checked);
              }}
              

인풋 자체가 제출돼 버렸어?

  • Conosle
    MeetupForm.tsx:163
    Submitted startedAt: <input id=​"startedAt" type=​"date" required name=​"startedAt">​

submitted isPublic: on이 체크박스의 체크 여부와 상관없이 항상 "on"으로 뜨는 이유는 다음과 같습니다:

원인
isPublicRef.current?.value를 사용하여 값을 가져오고 있기 때문입니다.

HTMLInputElement의 value 속성:
type="checkbox"인 경우, 체크박스의 값은 value 속성이 아닌 checked 속성을 통해 가져와야 합니다.
value 속성은 항상 HTML의 기본값("on" 또는 사용자 정의 값)을 반환하며, 체크 여부와는 상관이 없습니다.
해결 방법
isPublicRef.current?.checked를 사용하여 체크 여부를 확인해야 합니다.

수정 코드
handleMeetupFormSubmit에서 다음과 같이 수정합니다:

tsx
코드 복사
const isPublic = isPublicRef.current?.checked || false; // checked 속성을 사용
console.log("Submitted isPublic:", isPublic);

profile
아무튼, 개발자

0개의 댓글