Reputation: 31
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!
Upvotes: 3
Views: 7871
Reputation: 36989
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
}, [])
Upvotes: 2
Reputation: 734
Your ref is not initialize when setHidden set to false if you want to use it you need some interactions like this
import React, { useRef, useState, useEffect } from 'react';
function App() {
const [hidden, setHidden] = useState(true);
const inputRef = useRef(null)
console.log(inputRef);
const handleChange=()=>{
console.log(inputRef);
}
useEffect(()=>{
console.log(inputRef);
},[hidden])
return (
<div>
<input onChange ={handleChange}></input>
{!hidden && <h2 ref={inputRef}>Hello World</h2>}
{hidden && <button onClick={() => setHidden(false)}>Show Child</button>}
</div>
)
}
export default App;
Upvotes: 0