Created
January 2, 2023 09:06
-
-
Save nasheomirro/81e4af03c0fcc7559e6734fc4c46e87e to your computer and use it in GitHub Desktop.
react-hook-form utility function for attaching refs on register
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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