Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to listen for scroller other than document #11

Open
curran opened this issue Jul 19, 2019 · 1 comment
Open

Ability to listen for scroller other than document #11

curran opened this issue Jul 19, 2019 · 1 comment

Comments

@curran
Copy link

curran commented Jul 19, 2019

I tried this library, and hit a use case where the scroll listener needed to be added to a scrollable element inside some other elements. My solution looks something like this:

import { useEffect, useLayoutEffect, useCallback } from 'react';

// Inspired by https://github.com/Swizec/useDimensions
export const useDimensions = ({ wrapperRef, scrollerRef, setDomRect }) => {
  
  // Measures the current dimensions.
  const measure = useCallback(() => {
    setDomRect(wrapperRef.current.getBoundingClientRect());
  }, [wrapperRef, setDomRect]);

  // Handles the case that the first measure causes a vertical
  // scrollbar to be introduced, which throws off the transform.
  // requestAnimationFrame effectively waits for the scrollbar to appear.
  const measureTwice = useCallback(() => {
    measure();
    requestAnimationFrame(measure);
  }, [measure]);

  // Measure the initial dimensions.
  useLayoutEffect(measureTwice, [measure]);

  // Measure the dimensions on resize.
  useEffect(() => {
    window.addEventListener('resize', measureTwice);
    return () => {
      window.removeEventListener('resize', measureTwice);
    };  
  }, [measureTwice, scrollerRef]);

  // Measure the dimensions on scroll.
  useEffect(() => {
    if (scrollerRef) {
      const scroller = scrollerRef.current;
      scroller.addEventListener('scroll', measure);
      return () => {
        scroller.removeEventListener('scroll', measure);
      };  
    }   
  }, [measure, scrollerRef]);
};
@wmertens
Copy link

I saw that the current code uses callback-style refs, apparently at the behest of Dan Abramov. I thought they were being phased out, so I don't know why that is.

In any case, what if you want to measure document scroll anyway? How to yet get a ref to that? Wouldn't it be better to pass the actual element somehow?

Also, how does the getBoundingClientRect introduce a scrollbar? I can't find anything on that…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants