React userRef error Object is possibly null fix
Use type guards to resolve “Object is possibly null” errors with the useRef hook in React, for example if(inputRef.current){}
. Once null is excluded from the type of ref, we can access properties on the ref that correspond to its type.
Below is sample code that causes this error to occur.
import {useEffect, useRef} from 'react';
export default function App() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
// ⛔️ Object is possibly 'null'.ts(2531)
inputRef.current.focus();
}, []);
return (
<div>
<input ref={inputRef} type="text" id="message" />
<button>Click</button>
</div>
);
}
The problem in the code snippet is that TypeScript doesn't guarantee that we'll assign the ref to an element or assign it a value, so its current property may be null.
To fix this error, we must use type guards to exclude null from ref's type before accessing its properties.
import {useEffect, useRef} from 'react';
export default function App() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
// 这里 ref 可以是 null
if (inputRef.current != null) {
// TypeScript 知道这里的 ref 不为 null
inputRef.current.focus();
}
}, []);
return (
<div>
<input ref={inputRef} type="text" id="message" />
<button>Click</button>
</div>
);
}
We use a simple if statement as a type guard to ensure that the current property on the ref does not store a null value.
TypeScript knows that once we enter the if block, the current property of the ref object will not store a null value.
Make sure to use generics on the useRef hook to correctly type the current property of the ref
Notice that we pass a generic to the value of ref to the HTMLInputElement.
The types of DOM elements are uniformly named HTML***Element. Once you start typing HTML.., your IDE should be able to help you autocomplete.
Some commonly used types are: HTMLInputElement
, HTMLButtonElement
, HTMLAnchorElement
, HTMLImageElement
, HTMLTextAreaElement
, HTMLDivElement
etc.
If you store different values in the ref, make sure to pass the specific type to the useRef hook's generics, ·const ref = useRef<{name: string}>(null);
e.g.
(?.)
We can also use the optional chaining operator to block if the current property on the ref stores a null value .
import {useEffect, useRef} from 'react';
export default function App() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
// 👇️ optional chaining (?.)
inputRef.current?.focus();
}, []);
return (
<div>
<input ref={inputRef} type="text" id="message" />
{/* Cannot find name 'button'.ts(2304) */}
<button>Click</button>
</div>
);
}
If ref is empty (null or undefined), the optional chaining (?.)
operator will block rather than raise an error.
In other words, if the current property on ref stores a null value, the operator will short-circuit and return undefined, rather than attempting to call the focus() method on the undefined value and causing a runtime error.
Another solution to the “object might be null” error with refs in React is to use the not null (!) assertion operator.
import {useEffect, useRef} from 'react';
export default function App() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
// 👇️ using non-null (!) assertion
inputRef.current!.focus();
}, []);
return (
<div>
<input ref={inputRef} type="text" id="message" />
{/* Cannot find name 'button'.ts(2304) */}
<button>Click</button>
</div>
);
}
The exclamation mark is called the non-null assertion operator in TypeScript. It is used to remove null and undefined from a type without doing any explicit type checking.
When we use this, we basically tell TypeScript that the current property on the ref object does not store a value of null or undefined.
Note that this approach is not type-safe, as TypeScript does not perform any checks to ensure that the property is not null.
The “Object is possibly null” error is caused because the useRef() hook can be passed an initial value as a parameter, and we passed it null as the initial value.
The hook returns a mutable ref object whose .current
attributes are initialized to the passed arguments.
When we pass a ref prop to an element, for example <input ref={myRef} />
, React .current
sets the properties of the ref object to the corresponding DOM node, but TypeScript can't determine whether we mean to set the ref to the DOM element or to set its value later in our code.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:188 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:187 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:102 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:172 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:153 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:60 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:191 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:78 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:90 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap