Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  129] [ 7]  / answers: 1 / hits: 42706  / 4 Years ago, tue, june 16, 2020, 12:00:00

I have a text input. If I click on a specific button in the page, I want to reset the value of the input. Here is my code:





const inputRef = useRef()

const handleClick= () => {
inputRef.current.value.reset();
return hello world
}

return (
<>
<input type=text ref={inputRef}/>
<button onClick={()=> handleClick}>delete all</button>
</>
)





It doesn't work. How to fix this?


More From » reactjs

 Answers
7

You can clear the text input field by setting its value to an empty string. You can do that like this inputref.current.value = if you want to use uncontrolled inputs.



However, if you want to use controlled inputs you can create a state variable to track the value of the input field. For example,



const SomeComponent = () => {
const [text, setText] = useState('')

return (
<>
<input type=text value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={() => setText('')}>delete all</button>
</>
);
};



Here is a codesandbox with both implementation.


[#50870] Monday, June 1, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dannyc

Total Points: 517
Total Questions: 106
Total Answers: 116

Location: Netherlands
Member since Mon, Jun 7, 2021
3 Years ago
;