0

How do I add an addEventListener scroll to my div element? Currently I have below, but I get a Typescript ESLint error:

Property 'addEventListener' does not exist on type 'HTMLCollectionOf'.ts

const Overlay = ({ children }: Props) => {
  // const [fade, setFade] = useState(false);

  useEffect(() => {
    const element = document
      .getElementById('dialog')
      ?.getElementsByClassName('MuiDialog-paperScrollPaper');
    console.log(element);

    const onScroll = () => {
      console.log('Scrolled');
    };
    if (element) {
      element.addEventListener('scroll', onScroll);
    }
  }, []);

  return (
    <React.Fragment>
      <Dialog fullScreen open={open} id="dialog">
        <header id="header">
          // My header
        </header>
        {children}
      </Dialog>
    </React.Fragment>
  );
};

export default Overlay;
meez
  • 3,783
  • 5
  • 37
  • 91

1 Answers1

0

getElementsByClassName('MuiDialog-paperScrollPaper')

This returns a collection (HTMLCollection) not a single element

Next, read this to map or loop through the collection (to add your event listener to each found element: Most efficient way to convert an HTMLCollection to an Array

Khoa
  • 2,632
  • 18
  • 13