ElearningWorld.org

For the online learning world

Moodle

React Hook Form Submitting From Parent Component

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 noobb) I don’t have much time to work on this articlec) 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-943ilHere is a code sandbox using the “imperativeHandle” hook approach:https://codesandbox.io/s/react-hook-form-parent-submit-imperative-handle-7ty9vTwo approachesUse effectThis is my preferred approach. It works by doing two things -a) Managing a property via “useEffect” to track submission requestsb) 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.imperativeHandleThis 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();

blank
Follow me

Latest posts by EdTech Geek (see all)
blank

EdTech Geek

Server administrator, solutions architect, developer, EdTech enthusiast, and park-time geek.