Resetting form fields onsubmit in next js
In this post I am going to show you how you can reset your form fields on submit in any next js website.
First of let's create a basic JSX form template as shown below
<div>
<form id="SubmitForm" className={`${styles.form}`} onSubmit={SubmitForm}>
<h3 className={`${styles.heading}`}>Basic form example</h3>
<div >
<input name="username" placeholder="enter username" className={`${styles.form_field}`} type="text" />
</div>
<div >
<input name="email" placeholder="enter email" className={`${styles.form_field}`} type="email" />
</div>
<div >
<input name="password" placeholder="enter password" className={`${styles.form_field}`} type="password" />
</div>
<div className={`${styles.button_wrapper}`}>
<button className={`${styles.submit_button}`} type="submit">Submit</button>
</div>
</form>
</div>
Above is the JSX for a basic form in next js. As you can see from the code above onsubmission of our form a const SubmitForm is being called to handle the submission process.
Below is the Css used to style the form
.form{
display: grid;
justify-content: center;
background: #303f9f;
}
.heading{
color: white;
}
.form_field{
border-radius: 13px;
margin-bottom: 10px;
border: unset;
}
.button_wrapper{
display: flex;
justify-content: center;
}
.submit_button{
border-radius: 10px;
border: white 2px solid;
color: white;
background: unset;
}
If you don't know how to setup an external stylesheet for your next js website then read our How to use external stylesheets in next js post to get started
The final step is to create the SubmitForm const in our code as shown below;
const SubmitForm = (e) =>{
e.preventDefault();
var formData = new FormData(e.target);
const form_values = Object.fromEntries(formData);
console.log('www', form_values)
document.getElementById("SubmitForm").reset();
}
On clicking the submit button the forms data is consoled out in the browser and the form fields are reset by the "reset()" function attached to the form's id.
Conclusion
Through this short tutorial I have been able to show you how you can reset the fields of any form in your next js website.by using a simple basic jsx form example. Thanks for reading, any comments or questions regarding the post can be added in the comment section below.