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.
Before you attach your ref to the div ref.current
is undefined, add an if check in your effect to check if it's not undefined.
also, we should listen to the isLoading
state instead of the ref object.
const [isLoading, setIsLoading] = useState(true);
useEffect(
() => {
if (resultsRef.current) {
window.scrollTo({
behavior: "smooth",
top: resultsRef.current.offsetTop
});
}
},
[isLoading]
);
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