Home > Enterprise >  Use a useRef value to update a state value in React (Object is possibly null)
Use a useRef value to update a state value in React (Object is possibly null)

Time:09-22

I'm having an issue with useRef, where I am getting "object is possibly null" when trying to use it to set a stateful object.

const jselectRef = useRef<HTMLButtonElement>(null)
const [defaultHeight, setDefaultHeight] = useState<number>(0)
useEffect(() => {
    if (jselectRef.current !== null) {
        setDefaultHeight(jselectRef.current.offsetParent.clientHeight)
    }
}, [])
return (
    <>
        <button
            ref={jselectRef}
            style={{
                height: dropdownOpen ? defaultHeight * 10 : defaultHeight
            }}
        >
            <div className="jselect__current" style={{
                height: defaultHeight
            }}>
            </div>
        </button>
    </>

Normally, I would just change useState<number> to useState<number | undefined, then add a ? to the reference as so:

But now I get "Object is possibly undefined" wherever I use the variable. The thing is, in useEffect I have a nullcheck there, so the value being null literally isn't possible. It's either 0 (default) or it gets it's value from the ref.

I suppose I could use an if statement to check if it's undefined every time I use it, but is that really the best way? That seems like too much technical burden for TypeScript sake. Is there a way to accomplish this with TypeScript?

CodePudding user response:

The problem is that offsetParent can be null by spec.

So you need to either:

check that it isn't null:

useEffect(() => {
    if (jselectRef.current?.offsetParent !== null) {
        setDefaultHeight(jselectRef.current.offsetParent.clientHeight)
    }
}, [])

or default to a numeric value:

useEffect(() => {
    if (jselectRef.current) {
        setDefaultHeight(jselectRef.current.offsetParent?.clientHeight ?? 0)
    }
}, [])
  • Related