If you use uncontrolled form inputs, an input type of reset will reset the form inputs to their original values. Using controlled inputs, you must set each input state variable value to its default values.
Warning: The reset input will clear some input values even if you use controlled inputs. But the underlying state values will remain and cause unexpected behavior.
The reset property inside the form element is standard HTML. However, the reset button must be enclosed within an HTML form.
export const App = () => {
return(
<form>
<div><span>Name:</span><input/></div>
<br/>
<div><span>Address:</span><input/></div>
<br/>
<div>
<span>Status:</span>
<select value={status} onChange={(e) => setStatus(e.target.value)}>
<option value="">Select</option>
<option value="Customer">Customer</option>
<option value="Supplier">Supplier</option>
</select>
</div>
<br/>
<div><input type="reset" value="Reset Form"/></div>
</form>)
}
export default App
When you use controlled inputs, it is essential to reset the state variables that hold input values. To demonstrate that, I have included both reset methods in the below form.
I log the entered data in the table below the form. That is to illustrate the values held in the state variables. Note that the HTML reset button will clear the inputs on the HTML form (Select and Checkbox), but the state values remain.
import { useState } from "react"
export const App = () => {
const [name, setName] = useState<string>()
const [address, setAddress] = useState<string>()
const [status, setStatus] = useState<string>()
const [orders, setOrders] = useState<string>()
const resetForm = () => {
setName("")
setAddress("")
setStatus("")
}
const setOrdersCheckBox = (val: HTMLInputElement) => {
setOrders(val.checked ? val.value : "N")
}
return(
<>
<form>
<div><span>Name:</span><input value={name} onChange={(e) => setName(e.target.value)}/></div>
<br/>
<div><span>Address:</span><input value={address} onChange={(e) => setAddress(e.target.value)}/></div>
<br/>
<div>
<span>Status:</span>
<select value={status} onChange={(e) => setStatus(e.target.value)}>
<option value="">Select</option>
<option value="Customer">Customer</option>
<option value="Supplier">Supplier</option>
</select>
</div>
<br/>
<div><span>Orders:</span><input type="checkbox" value="Y" onChange={(e) => setOrdersCheckBox(e.target)}/></div>
<br/>
<div>
<input type="reset" value="HTML Reset Form"/>
<input type="button" value="Reset Form" onClick={() => resetForm()}/>
</div>
</form>
<br/>
{name && address && status &&
<table>
<tr><td>Entered Data</td></tr>
<tr><td>Name: {name}</td></tr>
<tr><td>Address: {address}</td></tr>
<tr><td>Status: {status}</td></tr>
<tr><td>Recent Orders: {orders}</td></tr>
</table>}
</>
)
}
export default App