Form: Component
Note: This component is currently in BETA
This component is optional and it takes care of the form submission by closely aligning with the standard native form.
By default, we will send a POST request with your form submission data as FormData. You can supply headers
prop to avoid FormData to be submitted and use application/json
instead.
Progressively enhancement for your form.
Support both React Web and React Native.
Take care of form submission handling.
<Formaction="/api"method="post" // default to postonSubmit={() => {}} // function to be called before the requestonSuccess={() => {}} // valid responseonError={() => {}} // error responsevalidateStatus={status => status >= 200} // validate status code/>
Props
All props all optional
Name | Type | Description | Example |
---|---|---|---|
control | Control |
|
|
children | React.ReactNode | ||
render | Function | Render prop function suitable for headless component. |
|
onSubmit | Function | Function invoked after successful validation. |
|
onSuccess | Function | Function called after successful request to the server. |
|
onError | Function | Function called after failed request to the server.
|
|
headers | Record<string, string> | Request headers object. |
|
validateStatus | (status: number) => boolean | Function to validate status code. |
|
Rules
If want to prepare or omit submission data, please use
handleSubmit
oronSubmit
.const { handleSubmit, control } = useForm();const onSubmit =(data) => callback(prepareData(data))<form onSubmit={handleSubmit(onSubmit)} />// or<Form onSubmit={({ data }) => { console.log(data) }} />Progressive Enhancement only applicable for SSR framework.
const { handleSubmit, control } = useForm({progressive: true});<Form onSubmit={onSubmit} control={control} action="/api/test" method="post"><input {...register('test', { required: true })} /></Form />// Renders<form action="/api/test" method="post"><input required name="test" /></form>
Examples
import { useForm, Form } from 'react-hook-form';function App() {const {control,register,formState: { isSubmitSuccessful, errors },} = useForm({// progressive: true, optional prop for progressive enhancement});return (<div>// Use action prop to make post submission with formData<Formaction="/api"control={control}onSuccess={() => {alert("Success");}}onError={() => {alert("error");}}><input {...register("name")} />{isSubmitSuccessful && <p>Form submit successful.</p>}{errors?.root?.server && <p>Form submit failed.</p>}<button>submit</button></Form>// Manual form submission<FormonSubmit={async ({ formData, data, formDataJson, event }) => {await fetch("api", {method: "post",body: formData,});}}><input {...register("test")} /><button>submit</button></Form></div>);}
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.