I would like to create a form where the submit button is located in the header. I'm currently using react-hook-forms but am having difficulties being able to submit the form from a component that is in the layout the displays the form (or child). I've included an image that may help visualize what im talking about.

Is there a way I can pass that form data or handleSubmit from react-hook-form to to the header that would then run the onSubmit when clicked?
Just create a ref in the parent component, send it to the child component and assign that ref to an invisible submit button.
Finally, in the onClick event of the parent submit button simply call submitRef.current.click()
// ./From.js
import React from 'react';
import { useForm } from 'react-hook-form';
// This is the child component with a ref received from the parent
// and assigned to an invisible submit button
const Form = ({ submitRef }) => {
const {register, setValue, getValues, ...other } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
...
<button ref={submitRef} type="submit" style={{ display: 'none' }} />
</form>
);
};
export default Form;
// ./Parent.js
import React, { useRef } from 'react';
import Form from './Form'
const Parent = () => {
const submitRef = useRef();
return (
<>
<button onClick={() => submitRef.current.click()}>Submit</button>
<Form submitRef={submitRef}/>
</>
);
};
export default Parent;
You can set ref on form:
<form ref={formRef} onSubmit={handleSubmit}>
and then simulate onSubmit from any place:
formRef.current.requestSubmit();
This behaves as submit button click, without inserting unnecessary submit button: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With