5
votes

I'm trying to understand how react-hook-form is working. For this I created the following example:

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

const InputForm = () => {
  const { register, handleSubmit } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <>
      <Form onSubmit={handleSubmit(onSubmit)}>
        <Form.Group controlId='formBasicName'>
          <Form.Label>Name</Form.Label>
          <Form.Control
            type='text'
            name='name'
            ref={register}
          />
        </Form.Group>

        <Form.Group controlId='formBasicEmail'>
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type='email'
            name='email'
            ref={register}
          />
          
        <Button className='submitBtn' type='submit'>
          Submit
        </Button>
      </Form>
    </>
  );
};

export default InputForm;

It works and if I submit the form I can see the data object in console. The only problem is that after each submit the input boxes are still showing their value. I want that after each submit the value of input boxes get empty. That would be easy with useState, but now that I'm using react-hook-from, I don't know how to do that.

4

4 Answers

12
votes

Use this submit function:

const onSubmit = (data, e) => {
  e.target.reset();
};

10
votes
const InputForm = () => {
  const { register, handleSubmit, reset } = useForm();

  const onSubmit = (data) => {
    console.log(data);
    reset();
  };

Add it to the submit function

4
votes

React Hook Forms v7. This will clear the form data.

    const {register, handleSubmit, formState: { errors }, reset} = useForm();

    const onSubmit = (data, e) => {
        console.log(data)
        reset('', {
            keepValues: false,
        })
    }
0
votes

Use the following code to reset the input fields

const onSubmit = (data, e) => {
  e.target[0].value = ''; // for name
  e.target[1].value = '';  // for email
};