0

I have a React app in which I have a TextBox and a button. When I click on the button I want the TextBox value to be cleared. How can I achieve this without using a form?

 const [name, setName] = useState('') 

 const handleChange = e => {
   setName(e.target.value)
 }

 const handleSubmit = () => {
  // clear the TextBox
}
 

 <input type="text" onChange={handleChange} />
 <button onClick={handleSubmit}></button>

2 Answers 2

2

Usually, in cases like this, input values are stored in state, which in your case it is called name

So you need to also map the input value to the state, then just set the value of name to nothing:

const [name, setName] = useState('') 

 const handleChange = (e) => {
   setName(e.target.value)
 }

 const handleSubmit = () => {
  setName('')
}
 
<input type="text" value={name} onChange={handleChange} />
<button onClick={handleSubmit}></button>
Sign up to request clarification or add additional context in comments.

Comments

1
const [name, setName] = useState('') 

 const handleChange = (e) => {
   setName(e.target.value)
 }

 const handleSubmit = () => {
  setName('') // clear the TextBox
}
 

 <input type="text" value={name} onChange = {handleChange}  />
 <button onClick = {handleSubmit}></button>

3 Comments

bcz your input was not controlled. i updated my ans. you have to pass your state as value of the input to make it controlled input
I added the value attribute on input type text and set the value to be the name and then it worked. Thanks!
React recommends to use controlled input. see details here: reactjs.org/docs/forms.html#controlled-components.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.