React Hook Form Submitting From Parent Component

NOTE: I’m publishing this in case it is useful to people but with the following disclaimers:

a) I’m a react noob

b) I don’t have much time to work on this article

c) The purpose of this article was for me to increase my skills more than to inform.

Very recently I’ve needed to call submit on a React Hook Form component from a parent component.

If you just want to dive into my code (feel free to criticize it as I’m a React noob), here is a code sandbox using the “useEffect” approach:

https://codesandbox.io/s/react-hook-form-parent-submit-useeffect-943il

Here is a code sandbox using the “imperativeHandle” hook approach:

https://codesandbox.io/s/react-hook-form-parent-submit-imperative-handle-7ty9v

Two approaches

Use effect

This is my preferred approach. It works by doing two things –

a) Managing a property via “useEffect” to track submission requests

b) Passing the submission request status and a parent callback method from a parent component to the child form props.

I prefer this because the code appears cleaner AND because the imperativeHandle hook is generally discouraged.

imperativeHandle

This approach allows you to expose a function to the parent component via “useImperativeHandle” hook.

You do this by wrapping your component in “forwardRef” — e.g:

export default forwardRef((props, ref) => { useImperativeHandle(ref, () => ({
submitForm() {
handleSubmit(onSubmit, onError)();
}
})});

This wrapping makes for uglier code IMO. The function invocation in the parent component also looks odd because it looks like a class method — e.g:

editFormRef.current.submitForm(); Source: https://brudinie.medium.com/feed

Generated by Feedzy
%d bloggers like this: