0

How about friends, I have an eventHandler added to a div that listens if the user scrolls to hide the navigation bar. It works fine since the container that performs the scroll function is the body, but if I add the overflow: scroll style to the div that contains my sections, the eventHandler doesn't work anymore. How can I add this same code to a div that contains the .layoutContainer class?

  useEffect(() => {
    window.addEventListener("scroll", handleScroll, { passive: true });
    window.addEventListener("touchmove", handleScroll, {
      passive: true,
    });
  }, []);

I tried doing getElementByClassName but it didn´t works. Hope you can help me, thank you

JDLR
  • 520
  • 1
  • 4
  • 20

1 Answers1

1

Like this?

// see https://stackoverflow.com/questions/35939886/find-first-scrollable-parent
function getScrollContainer(node) {
  while (node) {
    if (node.scrollHeight > node.clientHeight) {
      return node;
    }
    node = node.parentNode;
  }
  return null;
}

// we want a reference to the current DOM node
const ref = React.useRef(null);

useEffect(() => {
  // determine what element is scrolling
  const container = getScrollContainer(ref.current);
  if(!container) return;

  // add the event listener
  container.addEventListener("scroll", handleScroll, { passive: true });
  container.addEventListener("touchmove", handleScroll, { passive: true });

  return () => {
    // and clean up after yourself
    container.removeEventListener("scroll", handleScroll);
    container.removeEventListener("touchmove", handleScroll);
  }
}, [/* sure that this doesn't rely on some dependency, like some `isVisible` state? */]);

// set the ref so we get access to the DOM node
return <div ref={ref} ...

And unless this component gets added, and later removed on handleScroll, I'm almost certain that your effect should be executed based on some dependent value, and not just on componentDidMount

Thomas
  • 11,958
  • 1
  • 14
  • 23
  • Yeah thank you that works for sure i make it works and then saw your reply with this is the same way i did it, just need to use refs. Thank you so much – JDLR May 08 '20 at 23:39
  • @JoangelDeLaRosa, don't forget to remove the event listener. – Thomas May 08 '20 at 23:40