Skip to content

Form (BETA)

Take care form submission

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.

<Form
  action="/api"
  method="post" // default to post
  onSubmit={() => {}} // function to be called before the request
  onSuccess={() => {}} // valid response
  onError={() => {}} // error response
  validateStatus={status => status >= 200} // validate status code
/>

Props

All props all optional

NameTypeDescriptionExample
controlControl

control object provided by invoking useForm. Optional when using FormProvider.

<Form control={control} />
childrenReact.ReactNode
renderFunction

Render prop function suitable for headless component.

<Form 
  render={({ submit }) => <View />} 
/>
onSubmitFunction

Function invoked after successful validation.

<Form 
  onSubmit={data => mutation(data)} 
/>
onSuccessFunction

Function called after successful request to the server.

<Form 
  onSuccess={({ response }) => {}} 
/>
onErrorFunction

Function called after failed request to the server.

setError function will be called to update errors state.

<Form 
  onError={({ response }) => {}} 
/>
headersRecord<string, string>

Request headers object.

<Form 
  headers={{
    accessToken: 'xxx',
    // Json content type 
    // will stringify form data
    'Content-Type': 'application/json'
  }}
/>
validateStatus(status: number) => boolean

Function to validate status code.

<Form 
  validateStatus={status => status === 200}
/>
fetcher(action: string, options: Object) => void

Custom fetcher callback function

// with server state library
<Form 
  fetcher={
   (action, { values }) => axios(action, values})}
/>

// with custom axios
<Form 
  fetcher={
   (action, { values }) => mutation(values)}
/>

Rules

  • If want to prepare or omit submission data, please use handleSubmit or custom fetcher.

    const { handleSubmit, control } = useForm();
    const onSubmit =(data) => callback(prepareData(data))
    
    <form onSubmit={handleSubmit(onSubmit)} />
    // or
    <Form action="/api" control={control} fetcher={(action, { values }) => onSubmit(values)} />
    
  • 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>
    
  • It's sufficient enough to just use the handleSubmit callback with server state library, but you can use with SWR or TanQuery to support progressively enhancement.

    const { handleSubmit, control } = useForm({
      progressive: true                    
    });
    const [mounted, setMounted] = useState(false)
    const mutation = useMutation();
    
    <form onSubmit={handleSubmit(mutation)} />
    
    <Form fetcher={(action, { values }) => mutation(values)} action={'/api/something'/}>
    

Examples

import { useForm } from 'react-hook-form';

function App() {
  const { control, register, formState: { isSubmitSuccessful, errors } } = useForm({
    // progressive: true, optional prop for progressive enhancement
  });
  
  return (
    <Form action="/api" control={control}>
      <input {...register('name')} />
    
      {isSubmitSuccessful && <p>Form submit successful.</p>}
      
      {errors?.root?.server && <p>Form submit failed.</p>}
    
      <button>submit</button>
    </Form>
  )
}
import { uesForm } from 'react-hook-form';

function App() {
  const { control, register, formState: { isSubmitSuccessful, errors } } = useForm();
  
  return (
    <Form 
      action="/api" 
      control={control} 
      render={({ submit }) => {
        <View>
          {isSubmitSuccessful && <Text>Form submit successful.<Text>}
          
          {errors?.root?.server && <Text>Form submit failed.</Text>}
        
          <Button onPress={() => submit()} />
        </View>
      }}
    />
  )
}

Thank you for your support

If you find React Hook Form to be useful in your project, please consider to star and support it.

Edit