🧑‍🌾

【React】react-selectとreact-hook-formを合わせて使う

2021/10/29に公開

概要

以前に【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
          />
        )}
      />
    </>
  );
}

Discussion