How to clear input field value on button click in react?
May 26, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To clear or reset input value in react js, make input state empty when user click on the button that’s how you can clear input value in react js.
See the short example of clear input feild state value on the click of button.
<button onClick={() => setMessage('')}>Clear field</button>
Tip of the day: You can clear any input type text, number, textarea, date just making their value state empty.
Today, I am going to show you. How to clear input field value on button click in react with code example.
In this article we will see two below examples.
- Make empty input value on button click in react
- Make empty textarea on button click in react
Let’s start today’s tutorial how to reset input field in react
Make empty input value on button click in react
Here, we will do following things
- create Input feild componant.
- create state using
useState
hook - store the value of input field when user write anything.
- create a button componant.
- make input state empty or clear input value on the click of button.
APP.js
import { useState } from "react";
const App = () => {
const [message, setMessage] = useState("");
const handleChange = (event) => {
setMessage(event.target.value);
};
return (
<div>
<input
id="message"
name="message"
placeholder="Message"
type="text"
onChange={handleChange}
value={message}
/>
<button onClick={() => setMessage("")}>Reset</button>
</div>
);
};
export default App;
The output of the above program of reset input field value in react.
Here, we are provided code sandbox links for the above program for the reset input field value in react examples. Then you can use it whenever you want and do the changes as per your requirements.
Make empty textarea value on button click in react
Here, we will do following things
- create textarea componant.
- create state using
useState
hook - store the value of textarea when user write anything.
- create a button componant.
- make textarea state empty or clear textarea value on the click of button.
APP.js
import { useState } from "react";
const App = () => {
const [message, setMessage] = useState("");
const handleChange = (event) => {
setMessage(event.target.value);
};
return (
<div>
<textarea placeholder="Message" onChange={handleChange} value={message} />
<button onClick={() => setMessage("")}>Reset</button>
</div>
);
};
export default App;
The output of the above program of reset textarea value in react.
Here, we are provided code sandbox links for the above program for the reset textarea value in react examples. Then you can use it whenever you want and do the changes as per your requirements.
Happy Coding,
I hope the above example with help you to do your task.