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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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
@JoangelDeLaRosa, don't forget to remove the event listener.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.