Skip to content

Instantly share code, notes, and snippets.

@ygkn
Created September 24, 2024 03:46
Show Gist options
  • Save ygkn/c2f47ef83b4df66412c789d965eefea1 to your computer and use it in GitHub Desktop.
Save ygkn/c2f47ef83b4df66412c789d965eefea1 to your computer and use it in GitHub Desktop.
"use client";
import { type ReactNode } from "react";
import {
type Control,
type FieldPath,
type FieldPathValue,
type FieldValues,
useWatch,
} from "react-hook-form";
type Props<
TFieldValues extends FieldValues,
TFieldName extends FieldPath<TFieldValues>,
> = {
/**
* フィールドのパス
*/
name: TFieldName;
defaultValue?: FieldPathValue<TFieldValues, TFieldName>;
control?: Control<TFieldValues>;
disabled?: boolean;
exact?: boolean;
/**
* 要素を描画する関数
*/
render: (value: FieldPathValue<TFieldValues, TFieldName>) => ReactNode;
};
/**
* react-hook-form の動的に変化する値を使用できるコンポーネント
*
* 再レンダリング範囲はコンポーネント内に限定される
*
* @public
*/
export const Watch = <
TFieldValues extends FieldValues,
TFieldName extends FieldPath<TFieldValues>,
>({
render,
...props
}: Props<TFieldValues, TFieldName>): ReactNode => {
const value = useWatch<TFieldValues, TFieldName>(props);
return render(value);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment