Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using react useRef() --why my ref is null?

I have a simple example

function Node() {
    const [hidden, setHidden] = useState(true);
    const inputRef = useRef(null)
    console.log(inputRef);
    return (
        <div>
            {!hidden && <h2 ref={inputRef}>Hello World</h2>}
            {hidden && <button onClick={() => setHidden(false)}>Show Child</button>}
        </div>
    )
}

Upon clicking the button, I would expect that the h2 DOM element is attached to my ref. However, I found that the ref.current is still null upon logging, but if I expand the object, it contains the DOM node.

How am I supposed to access the DOM element via my ref? At the time I want to reference it, for example inputRef.current.getBoundingClientRect(), it's always shown as null. Your help is much appreciated!

like image 981
konghu Avatar asked Jul 10 '26 01:07

konghu


1 Answers

You are trying to use the ref in the render phase, but the ref will be populate once React paint the screen, in the commit phase. So, call it in a useEffect or useLayoutEffect

// run synchronously after all DOM mutations
React.useLayoutEffect(() => {
  // do something with inputRef
}, [])
like image 132
Federkun Avatar answered Jul 13 '26 16:07

Federkun