I have created a TextArea and set up a ref. I added a button which randomly assigns value to the ref. however when I mouse over on it, the value disappears.
const textareaRef = React.useRef(null);
const onAddFeature = () => {
if (textareaRef.current) {
//@ts-ignore
textareaRef.current.value = Math.random().toString(32);
}
<Textarea
ref={textareaRef}
onChange={(e) => console.log(e.target.value)}
size="sm"
/>
<Button
onPress={onAddFeature}
isIconOnly
size="sm"
variant="solid"
color="primary"
/>
I tried the ref. It doesn’t work not only on the TextArea component but also on the Input component.
3
Answers
I believe the TextArea component might have an internal value state which is not updated with your use of the ref. After a render the value is returned to the internal value state.
The proper way to accomplish what you want is to use useState instead of useRef and pass in a value prop to TextArea.
For the cases when you need to show up something on your React components, think of using
useState()
before, in most cases it is the right one to use.The
useRef()
doesn’t make the component to re-render, so, in most cases, nothing will happen on the screen when it values changes or it will cause some strange bugs like yours.Maybe there’s some
CSS
or something in your code that make the component re-render when hovering the Textarea and the value on theuseRef
reseted to null, like the initial state of it, so I recommend usinguseState()
for that cases:There is a lot of things wrong with the above code you provided, syntactically, logically and according to the rules of hooks in react.
Given the number of errors and the kind of errors I kindly recommend you to read the official documentation to learn more about React and its core principles.