[React] react-select와 react-hook-form을 조합하여 사용

6211 단어 Reacttech

개요


이전에 [React] react-select를 통해 사용자 정의 필터 설정의 글에서react-select의 프로그램 라이브러리를 소개했다.이react-select와React를 사용하는 폼 라이브러리react-hook-form을 조합해서 사용할 때 어떻게 해야 하는지 기록합니다.

대응 방법


여기.stackoverflow의 글에서 보듯이react-hook-form의 Controller 기능을 사용합니다.
Controller는react-hook-form문서과 같이react-hook-form과 외부 라이브러리를 조합하는 데 사용되는 잠금 구성 요소입니다.

샘플


Stackoverflow의 글과 기본적으로 같으니 먼저 실크 샘플을 넣으세요.
SampleComponent.js
export default function SampleComponent() {
  const options = [
    { value: "1_value", label: "1_label" },
    { value: "2_value", label: "2_label" },  
    { value: "3_value", label: "3_label" }   
  ];
  const { methods, control } = useForm();
  
  return (
    <>
      <Controller
        methods={methods}
        name="selectValue"
        rules={{ required: true }}
        control={control}
        render={({ onChange, value, name, ref }) => (
          <Select
            inputRef={ref}
            options={options}
            value={options?.find((c) => c.value === value)}
            onChange={(val) => {
              onChange(val?.value);
            }}
            isClearable
          />
        )}
      />
    </>
  );
}

좋은 웹페이지 즐겨찾기