Home > Net >  How can i reset react form all input field?
How can i reset react form all input field?

Time:04-30

I used React Hooks Form library for my project. But I can't able to reset after submitting data. Below, I have added my code.

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

  const onSubmit = (data) =>{
    const url = `http://localhost:5000/products`; 
    fetch(url,{
      method: 'POST', 
      headers: {
        'content-type': 'application/json'
      },
      body: JSON.stringify(data)
    })
    .then(res=>res.json())
    .then(data=>{
      toast("successfully added product"); 
    });  
  };

  return (
    <div className='container border-2'>
      <PageTitle title={"Add Product"}></PageTitle>
      <div className="">
        <h4 className='mt-5'>Add Items</h4><hr />
        <form onSubmit={handleSubmit(onSubmit)} className="d-flex flex-column w-50 mx-auto">
          <input className='mb-3 p-1' type="text" name="itemName" placeholder='Item Name' {...register("itemName", { required: true })}/>
          <input className='mb-3 p-1' type="text" name="imgLink" placeholder='Image URL' {...register("imgLink", { required: true })}/>
          <input className='mb-3 p-1' type="textarea" name="description" placeholder='Product Description' {...register("description", { required: true })}/>
          <input className='mb-3 p-1' type="number" name="price" placeholder='Product Price' {...register("price", { required: true })}/>
          <input className='mb-3 p-1' type="number" name="quantity" placeholder='Quantity' {...register("quantity", { required: true })}/>
          <input className='mb-3 p-1' type="text" name="supplierName" placeholder='Supplier Name' {...register("supplierName", { required: true })}/>
          <input type="submit" value="Add Item" className='btn btn-primary' />
        </form>
      </div>
      <ToastContainer />
    </div>
  );
};

Without React hooks form, i used to reset form data.target.reset(); . how can i reset all input field? Please if you know this, say somethings. Thanks in advance...

CodePudding user response:

To reset form data using react-hook-form,

  1. First, import reset module from react-hook-form like below
const { register, handleSubmit, reset } = useForm();
  1. And then use reset module
const onSubmit = (data) =>{
...
reset() // Reset All field
reset({"itemName": "item"}) // Reset with values
}

CodePudding user response:

You can reset the entire form or partial fields using the reset hook returned from useForm()

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

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

Have a look at the documentation here

  • Related