TextArea field with ref doesn't work as expected

70 Views Asked by At

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.

2

There are 2 best solutions below

3
Lucas Araujo On

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.

const [value, setValue] = React.useState();

const onAddFeature = () => {
   setValue(Math.random().toString(32));
}

...

 <Textarea        
 value={value}
 onChange={(e) => console.log(e.target.value)}
 size="sm" 
  />

...
0
Fabio Nettis On

There is a lot of things wrong with the above code you provided, syntactically, logically and according to the rules of hooks in react.

// This should be a component instead of a function that returns random jsx.
export default function AddFeature() {
  // needs to be inside the function component
  const textareaRef = React.useRef(null);

  // create a function that changes the value
  const onRandom = () => {
    // personally I would have chosen state over a ref
    textareaRef.current.value = Math.random().toString(32);
  };

  // return both the button and textarea from component
  return (
    <>
      <Textarea
        size="sm"
        ref={textareaRef}
        onChange={(e) => console.log(e.target.value)}
      />

      <Button
        isIconOnly
        size="sm"
        variant="solid"
        color="primary"
        {/* is this react-native? If not call onClick instead */}
        onPress={onRandom}
      />
    </>
  );
}

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.