0

I am using a ref created using createRef to store a string value in a class component. However, whenever I try to change the value of current, I get the error that current is ready only. I am using typescript:

class MyClassComponent extends React.Component {
  myRef = React.createRef<string>();

  someFunction = () => {
    this.myRef.current = 'value'; //error here: current is ready only.
  };
}
Saad Farooq
  • 39
  • 1
  • 8
  • 1
    Does this answer your question? [How to use React.useRef() in class component?](https://stackoverflow.com/questions/62499061/how-to-use-react-useref-in-class-component) – Emanuele Scarabattoli Jun 22 '23 at 09:01
  • You might also want to have a look at https://stackoverflow.com/questions/65329431/how-to-properly-use-ref-with-a-react-class-component-and-styled-components – Flo Jun 22 '23 at 09:07

2 Answers2

0

React 18.2.0, @types/react 18.2.13

React.createRef() returns the RefObject type which the .current property is read-only. We can declare the React.MutableRefObject type for myRef.

current: Initially, it’s set to null.

So the final type is React.MutableRefObject<string | null>.

interface MutableRefObject<T> {
    current: T;
}
interface RefObject<T> {
    readonly current: T | null;
}
class MyClassComponent extends React.Component {
  myRef: React.MutableRefObject<string | null> = React.createRef();

  someFunction() {
    this.myRef.current = 'value'; 
  }
}

stackblitz

Also, have a look at this issue

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • This will give the following error though: `TS2322: Type 'RefObject' is not assignable to type 'MutableRefObject'.` – Flo Jun 22 '23 at 09:10
0

createRef will give you a RefObject to pass as a ref property, the current field of this is readonly.

If you need a mutable reference (commonly used as state that can be changed without triggering a re-render), consider switching to a functional component and use useRef.

const MyComponent = () => {
    const myRef = React.useRef<string>()

    const someFunction = () => {
        myRef.current = 'value'; // works, will NOT trigger re-rendering of the component
    }

    return <p> Some Content here... </p>
}
Flo
  • 161
  • 1
  • 6