Sometimes, we want to clear an input value after form submission in a React app.
In this article, we’ll look at how to clear an input value after form submission in a React app.
Clear an Input Value After Form Submission in a React App
To clear an input value after form submission in a React app, we can set the value of the input value states after the form is submitted.
For instance, we can write:
import { useState } from "react";
export default function App() {
const [city, setCity] = useState("");
const onHandleSubmit = (e) => {
e.preventDefault();
setCity("");
};
return (
<div className="App">
<form onSubmit={onHandleSubmit}>
<input
onChange={(e) => setCity(e.target.value)}
value={city}
type="text"
/>
<button type="submit">Search</button>
</form>
</div>
);
}
We create the city
state with the useState
hook.
Then we create the onHandleSubmit
function that’s run when we submit the form with the Search button.
In the function, we call e.preventDefault()
to prevent the default server-side form submission behavior.
Then we call setCity
with an empty string to empty the city
value, which is used as the value of the input.
In the input, we set the onChange
prop to a function that calls setCity
to set the city
value to e.target.value
, which has the inputted value.
And in the form element, we set onSubmit
to onHandleSubmit
to run the it when we submit the form.
Conclusion
To clear an input value after form submission in a React app, we can set the value of the input value states after the form is submitted.