I wanted to ask this question again but ask now how I can achieve this using functions/hooks.
I've tried to use useRef and then access the offset form current.offsetTop, however I'm struggling accessing this ref after the component was mounted.
function ScrollComponent(props) {
const foo = false; //loading method
let resultsRef = useRef();
useEffect(() => {
window.scrollTo({
behavior: "smooth",
top: resultsRef.current.offsetTop
});
}, [resultsRef]);
if (foo)
return (
<div>
<h4>Loading...</h4>
</div>
);
return (
<div ref={resultsRef}>
<h4>content</h4>
</div>
);
}
In the above example, I have a const called foo which doesn't need to have this scroll ref attached to as it shows when the content is loading.
However, when running this code I get Cannot read property 'offsetTop' of undefined
In my useEffect method, I specify the dependency as the resultsRef so I expect it to only be called when the resultsRef gets written to when the content div loads, however, this is not the case.