Resetting to the initial state after form submission or cancelling a form submission is an integral part of the user experience when creating forms in ReactJS.
This morning I was trying to find a way to reset the form I was working on. I found this to be the most effective way to reset a form
// declaring the initial state
const initialState = { fname: "", lname: "", email: ""}
const [eachEntry, seteachEntry] = useState(initialState);
const {fname, lname, email} = eachEntry
...// function to handle onSubmit event
const handleSubmit = event => {
event.preventDefault(); axios.post('http://some.url/api', {
// some javascript object
}).then(() => {
event.target.reset();
}
}return(
<div>
<form onSubmit={handleSubmit}>
// some form input
</form>
</div>
)
This is a simple way to reset state when using hooks in ReactJS
Comments
Post a Comment