0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】React Hook FormでsetValueを使って保持している値をコンポーネントで描画する

Posted at

はじめに

React Hook Formregisterを使わずに、setValueを使うと、描画時にRHF側のstateとinputタグへの入力内容が一致しないことを解決した備忘録です。

実装例

・onDropの中でsetValueを使ってRHF側のstateを書き換えています。
getValuesを使って値を取得して、コンポーネントで描画しています。

export function ImageDragAndDropZone() {
  const { setValue, getValues } = useFormContext();

  const onDrop = (files: File[]) => {
    const droppedImage = files[0];

    // RHF側で一元管理する
    // 本来はサーバ側に処理を投げて、画像保存 + パスをDBに保存
    const imageUrl = URL.createObjectURL(droppedImage);
    setValue("imageSrcPath", imageUrl);
  };

  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  const imageSrcPath = getValues("imageSrcPath");

  return (
    <>
      <ToastContainer />
      <div
        {...getRootProps()}
        className={
          isDragActive
            ? "border-2 border-dotted rounded-lg border-red-400 h-3/6"
            : "border-2 border-dotted rounded-lg border-gray-300 h-3/6"
        }
      >
        {imageSrcPath && (
          <Image
            src={imageSrcPath}
            alt="プレビュー画像"
            width={9999}
            height={9999}
            className="h-full object-contain"
          />
        )}
        <input {...getInputProps()} />
        {!imageSrcPath && (
          <p
            className={
              isDragActive
                ? "text-gray-600 flex justify-center items-center h-full text-center"
                : "text-gray-400 flex justify-center items-center h-full text-center"
            }
          >
            ここにアップロードしたい画像をドラッグ&ドロップしてください。
          </p>
        )}
      </div>
    </>
  );
}

さいごに

setValueだと再レンダリングが引き起こされないので、getValueの値が更新されないと書いているのですが、
私の環境では、setValueでも再レンダリングされて値が更新されているようです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?