react-hook-form error

이보경·2024년 1월 11일

📌 문제

handleSubmit 동작하지 않는 에러

이상하게도 form 입력값들을 아무것도 건들지 않고 제출버튼을 누르면 handleSubmit 함수가 작동되지 않았다. (handleSubmit에는 validate 함수가 들어있는 상황)
알고보니 아래와 같은 에러들이 발생하고 있었고, 다음과 같이 해결하니 자연스럽게 해결되었다.


📌 원인 및 해결

input

Warning: 'value' prop on 'input' should not be null. Consider using the empty string to clear the component or 'undefined' for uncontrolled components.

<input type="text" value={value || ''}/>


radio

Warning: You provided a checked prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultChecked. Otherwise, set either onChange or readOnly.

onClick 핸들러와 checked 속성을 동시에 사용하면 안된다는 내용

  1. checked 속성 대신에 defaultChecked 속성을 사용한다.
  2. onClick 대신에 onChange 핸들러를 사용한다.
  3. onClick을 사용하고 싶으면 readOnly 속성을 추가한다.

<input type="radio" value={item} checked={field.value === item} onChange={field.onChange} />

// 전체 코드
const RadioButtonGroupRHF: React.FC<PropsType> = ({ radioList, name }) => {
  const { control } = useFormContext();

  return (
    <Controller
      control={control}
      name={name}
      render={({ field }) => (
        <fieldset {...field}>
          {radioList.map((item) => (
            <label key={item}>
              <input type="radio" value={item} checked={field.value === item} onChange={field.onChange} />
              <span>{item}</span>
            </label>
          ))}
        </fieldset>
      )}
    />
  );
};

other library (tagify)

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

React Hook Form과 같이 ref를 기반으로 동작하는 라이브러리를 사용한다면 고려할 수 있는 문제

react-hook-form이 ref를 자식컴포넌트에 전달하기 때문에 발생한 에러
react props는 ref를 전달하지 못한다

  1. 컴포넌트
    ref를 props로 사용하려면 forwardRef를 사용
    자식 컴포넌트를 forwardRef()함수로 감싸주고, props와 ref를 받아 사용

const Input = forwardRef((props, ref) => { return <input ref={ref} />; });

  1. cotroller (ref 공유)
    https://stackoverflow.com/questions/67877887/react-hook-form-v7-function-components-cannot-be-given-refs-attempts-to-access
    https://react-hook-form.com/faqs

  2. 내가 사용한 라이브러리는 ... field를 전체 스프레드하지 않고 필요한 것만 사용하는 것으로 변경했다.

// 전체 코드
import Tags from "@yaireo/tagify/dist/react.tagify";
import { Controller, useFormContext } from "react-hook-form";

const TagInputRHF = () => {
  const { control } = useFormContext();

  return (
    <Controller
      control={control}
      name="tags"
      render={({ field }) => (
        <Tags
          // {...field}
          defaultValue={field.value}
          onChange={(e) => {
            const values = e.detail.tagify.value.map((item) => item.value);
            field.onChange(values);
          }}
        />
      )}
    />
  );
};

0개의 댓글