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!
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
}, [])
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