Skip to content

Instantly share code, notes, and snippets.

@nasheomirro
Created January 2, 2023 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasheomirro/81e4af03c0fcc7559e6734fc4c46e87e to your computer and use it in GitHub Desktop.
Save nasheomirro/81e4af03c0fcc7559e6734fc4c46e87e to your computer and use it in GitHub Desktop.
react-hook-form utility function for attaching refs on register
import { MutableRefObject } from "react";
import {
FieldPath,
FieldValues,
RegisterOptions,
UseFormRegister,
} from "react-hook-form";
/** attach your ref to the register function from react-hook-form */
export const registerWithRef = <T extends FieldValues = FieldValues>(
register: UseFormRegister<T>,
) => {
return <Ref, N extends FieldPath<T>>(
name: N,
// add ref attribute to second arg of register
options: RegisterOptions<T, N> & { ref: MutableRefObject<Ref> },
): ReturnType<typeof register> => {
// modify returned ref so that we also attach the instance to our ref.
const { ref, ...newOptions } = options;
const { ref: returnedRef, ...rest } = register(name, newOptions);
// eslint-disable-next-line
const newRef = (e: any) => {
returnedRef(e);
ref.current = e;
};
return { ref: newRef, ...rest };
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment