0

I have this code for set scroll event to window and my container, but I think it is not good to use document in react component

   const closeMenu = () => {
        setIsActionListVisible(false);
    };

useEffect(() => {
        window.addEventListener("scroll", closeMenu);
        const layout = document.getElementsByClassName("common-home-layout");
        if (layout) {
            layout[0].addEventListener("scroll", closeMenu);
        }
    }, []);

Maybe do you have any better case for that?

3
  • Why would you use getElementsByClassName instead of querySelector? Commented Oct 16, 2022 at 13:23
  • I think, shouldn't use document inside the component Commented Oct 16, 2022 at 13:27
  • Does this answer your question? How to add event listener to a ref? Commented Oct 16, 2022 at 13:33

1 Answer 1

1

You can use useRef instead of document

const layoutRef = useRef();
if (layoutRef && layoutRef.current) {
  listRef.current.addEventListener(...)

  return () => {
    layoutRef.current.removeEventListener(...)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.