Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to an element with hooks/functions?

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.

like image 479
DanielJ Avatar asked May 10 '19 23:05

DanielJ


Video Answer


1 Answers

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]
);
like image 76
Asaf Aviv Avatar answered Oct 05 '22 23:10

Asaf Aviv