JDLR
JDLR

Reputation: 600

Event listener on className element, React Js

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

Upvotes: 0

Views: 2461

Answers (1)

Thomas
Thomas

Reputation: 12637

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

Upvotes: 1

Related Questions