7

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.

Flip
  • 6,233
  • 7
  • 46
  • 75
DanielJ
  • 729
  • 2
  • 7
  • 26

1 Answers1

13

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]
);
Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45
  • Thanks, I tried that but then the code never gets called. the useEffect code gets called when the loading return is called but not when the content is called. – DanielJ May 11 '19 at 00:47
  • Ah my bad we should add loading as our dependency instead of resultRef, will edit in a sec. – Asaf Aviv May 11 '19 at 00:49
  • Thanks, that worked great. Why do I need to use loading as a dependency? when isn't the thing changing the ref object? – DanielJ May 11 '19 at 00:55