头图

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) .

react-cannot-assign-to-current-because-read-only.png

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 example ref is of type string or null and its current 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.


chuck
303 声望41 粉丝