Reputation: 375
I'm a beginner at React. I'm trying to build a component that recovers the text of an input and later on inserts it on the HTML.
import React, { useState } from 'react';
function InputGetter(){
const [text, setText] = useState("")
let typed = ""
return(
<div>
<input type='text' onChange = {(e)=> typed = e.target.value}></input>
<button onClick={() => setText(typed)}>Set Text</button>
Text typed was "{text}"
</div>
)
}
export default InputGetter
The code above works for clicks when there's a change triggered. However, when I try to double click it, even when there's content on the input, text
somehow is set to ""
. I'm not sure why it happens. How can I make the text
variable content persistent?
Upvotes: 0
Views: 51
Reputation: 53874
You have closure on text
value within the onClick
callback, to persist value between renders, you can use useRef
hook, see Is there something like instance variables?.
function InputGetter() {
const [text, setText] = useState('');
const inputRef = useRef('');
return (
<div>
<input type="text" ref={inputRef}></input>
<button onClick={() => setText(inputRef.current.value)}>Set Text</button>
Text typed was "{text}"
</div>
);
}
Upvotes: 1