The text starts here~
Overview
"Cannot assign to 'current' because it does not include null
" when we initialize a ref
with a null
value is a read-only property" error. To resolve the error, include ---963d8ff80936e2e1c9a05626d2012984 ref
in the type of null
. For example, const ref = useRef<string | null>(null)
.
Here is an example to show how the error occurs.
// App.tsx
import {useEffect, useRef} from 'react';
const App = () => {
const ref = useRef<string>(null);
useEffect(() => {
// ⛔️ Error: Cannot assign to 'current' because it is a read-only property.ts(2540)
ref.current = 'hello';
}, []);
return (
<div>
<h2>hello world</h2>
</div>
);
};
export default App;
The problem with the above example is that when we pass null
as the initial value into the useRef
hook, and the generic we pass to the hook does not include null
type, we created an immutable ref
object.
correct generics
To fix the error, we have to include the null
type in the generic passed to the hook.
// App.tsx
import {useEffect, useRef} from 'react';
const App = () => {
// 👇️ include null in the ref's type
const ref = useRef<string | null>(null);
useEffect(() => {
ref.current = 'hello';
}, []);
return (
<div>
<h2>hello world</h2>
</div>
);
};
export default App;
In the type of ref
we use the union type to include the type null
which makes it a variable ref
object.
Now in this exampleref
is of type string ornull
and itscurrent
attribute can be assigned a value of either type.
DOM element
The same is true if your reference points to a DOM element. If you need to change the value of the ref
current
property of ---5d700fb88f9cc9e6c69a603ac0bba3ca---, you must set the hook type to const ref = useRef<HTMLElement | null>(null)
.
Note that you don't have to include null
ref
in the type of ---089d75ff8a267bfe410d15917dd50585--- if you don't assign it directly to the current
property.
// App.tsx
import {useEffect, useRef} from 'react';
const App = () => {
const ref = useRef<HTMLInputElement>(null);
useEffect(() => {
ref.current?.focus();
}, []);
return (
<div>
<input ref={ref} type="text" defaultValue="" />
</div>
);
};
export default App;
The ref
in the above example is used to focus the input
element. Since there is no assignment to its .current
property, there is no need to include null
in its type.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。