Sometimes, we want to clear and reset form input fields in our React app.
In this article, we’ll look at how to clear and reset form input fields in our React app.
Clear and Reset Form Input Fields
If we have a form that has a onSubmit prop set to a submit handler function. we can call reset to reset the form values.
For instance, if we have:
<form onSubmit={this.handleSubmit.bind(this)}>
{/* ... */}
</form>
Then our handleSubmit method can be written as:
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
We call reset to reset all the fields in the form.
This works for uncontrolled form fields.
If we have controlled form fields, then we’ve to reset the state to the original values.
For example, we can write:
import React, { Component } from 'react'
class NameForm extends Component {
initialState = { name: '' }
state = this.initialState
handleFormReset = () => {
this.setState(() => this.initialState)
}
onChange = (e) => {
this.setState({ name: e.target.value });
}
render() {
return (
<form onReset={this.handleFormReset}>
<div>
<label htmlFor="name">name</label>
<input
type="text"
placeholder="name"
name="name"
value={this.state.name}
onChange={this.onChange}
/>
</div>
<div>
<input
type="submit"
value="Submit"
/>
<input
type="reset"
value="Reset"
/>
</div>
</form>
)
}
}
We can set the onReset prop of the form to the handleFormReset method so that we set the form values back to the original values by setting the state to the initialState .
Since we have an input element with type set to reset , when that’s clicked, the function that we passed into the onReset prop will run.
Conclusion
If we have a form that has a onSubmit prop set to a submit handler function. we can call reset to reset the form values.