To clear or reset the input field in reactjs, the basic idea is to set the state handling the value of that input field to an empty string
.
TL;DR
function InputField() {
// State to store value from the input field
const [inputValue, setInputValue] = useState("");
// Input Field handler
const handleUserInput = (e) => {
setInputValue(e.target.value);
};
// Reset Input Field handler
const resetInputField = () => {
setInputValue("");
};
return (
<div>
{/* Input Field */}
<input type="text" value={inputValue} onChange={handleUserInput} />
{/* Reset button */}
<button onClick={resetInputField}>Reset</button>
</div>
);
}
Explanation
To understand it better let's first create
- an input field
- a
Reset
button to reset or clear the contents in the input field
It can be done like this,
function InputField() {
return (
<div>
{/* Input Field */}
<input type="text" />
{/* Reset button */}
<button>Reset</button>
</div>
);
}
Now let's initialize a state using the useState
react hook to store the value entered by the user.
Also, let's initialize the inputValue
state to the input field's value attribute and make a function to take user input. Check out How to get user input value from an input tag in Reactjs? to know more.
it can be done like this,
function InputField() {
// State to store value from the input field
const [inputValue, setInputValue] = useState("");
// User Input handler
const handleUserInput = (e) => {
setInputValue(e.target.value);
};
return (
<div>
{/* Input Field */}
<input type="text" value={inputValue} />
{/* Reset button */}
<button>Reset</button>
</div>
);
}
Now we have mapped the inputValue
state to the input field.
Now is the part we were looking for, to clear the input field on clicking the Reset
button, for that we can attach an onClick
handler function to set the state of inputValue
to an empty string ""
.
It can be done like this,
function InputField() {
// State to store value from the input field
const [inputValue, setInputValue] = useState("");
// Input Field handler
const handleUserInput = (e) => {
setInputValue(e.target.value);
};
// Reset Input Field handler
const resetInputField = () => {
setInputValue("");
};
return (
<div>
{/* Input Field */}
<input type="text" value={inputValue} onChange={handleUserInput} />
{/* Reset button */}
<button onClick={resetInputField}>Reset</button>
</div>
);
}
That's it! 🔥.
See the above code in action at Codesandbox.
Top comments (0)