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.
};
}
2
Answers
React 18.2.0, @types/react 18.2.13
React.createRef()
returns theRefObject
type which the.current
property is read-only. We can declare theReact.MutableRefObject
type formyRef
.So the final type is
React.MutableRefObject<string | null>
.stackblitz
Also, have a look at this issue
createRef
will give you a RefObject to pass as aref
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
.