Using React Hooks, I run into a TypeScript error when I initialize a ref as null, then try to access it later. This is a pared-down, illustrative example:
const el = useRef(null);
useEffect(() => {
if (el.current !== null) {
//@ts-ignore
const { top, width } = el.current.getBoundingClientRect();
}
}, []);
return <div ref={el}></div>
The @ts-ignore
suppresses the error Object is possibly 'null'.
Is it possible to write this without getting the error?
Autofocusing using React useRef() and useEffect() Hooks We can also get the same functionality with the useRef() and useEffect() React Hooks. Here is the same form using these Hooks: import React, { useRef, useEffect } from "react"; const Form = () => { const emailInput = useRef(null); useEffect(() => { if (emailInput.
The "Object is possibly null" error is caused because the useRef() hook can be passed an initial value as an argument and we're passing it null as an initial value. The hook returns a mutable ref object whose . current property is initialized to the passed argument.
The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.
If you want to update data and cause a UI update, useState is your Hook. If you need some kind of data container throughout the component's lifecycle without causing render cycles on mutating your variable, then useRef is your solution.
I found the answer here: https://fettblog.eu/typescript-react/hooks/#useref
The key is to assign a type to the ref:
const el = useRef<HTMLDivElement>(null);
then check carefully:
if (el && el.current){
const { top, width } = el.current.getBoundingClientRect();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With