Clearing the input field value in React
In this tutorial, we are going to learn about how to clear an input field value in react by clicking a form submit button.
We mostly clear the input field values whenever we submit a form or resetting the cluttered form.
Clearing the input field values
If you are using controlled components, it means your form (input) data is controlled by the react state, so that you can clear an input field value by assigning an empty string ''
to the react state.
Here is an example:
import React, { useState } from "react";
export default function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
function handleSubmit(e) {
e.preventDefault();
console.log(email, password);
// clearing the values
setEmail(""); setPassword(""); }
return (
<form>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit" onClick={handleSubmit}> Login </button> </form>
);
}
In the above example, we are clearing the email
, password
input field values whenever a user clicks on the login
button.
Similarly, if you are using uncontrolled components where your form input data is handled by dom itself instead of react state where you can clear it like this.
import React from "react";
export default function Login() {
function handleSubmit(e) {
e.preventDefault();
console.log(this.email.value, this.password.value);
// clearing the values
this.email.value = ""; this.password.value = ""; }
return (
<form>
<input
type="email"
placeholder="Email"
ref={(el) => (this.email = el)} /> <input
type="password"
placeholder="Password"
ref={(el) => (this.password = el)} />
<button type="submit" onClick={handleSubmit}>
Login
</button>
</form>
);
}