Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

give div event listener functional component

import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  // set default value
  const [scrollTop, setScrollTop] = useState(document.body.scrollTop);

  // create element ref
  const innerRef = useRef(null);

  useEffect(() => {
    const div = innerRef.current;
    // subscribe event
    div.addEventListener("scroll", handleOnScroll);
    return () => {
      // unsubscribe event
      div.removeEventListener("scroll", handleOnScroll);
    };
  }, []);

  const handleOnScroll = (e) => {
    // NOTE: This is for the sake of demonstration purpose only.
    // Doing this will greatly affect performance.
    setScrollTop(e.target.scrollTop);
  }

  return (
    <>
      {`ScrollTop: ${scrollTop}`}
      <div
        style={{
          overflow: 'auto',
          width: 500,
          height: 500,
          border: '1px solid black',
        }}
        ref={innerRef}
      >
        <div style={{ height: 1500, width: 1500 }}>
          Scroll Me
        </div>
      </div>
    </>
  )
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #give #div #event #listener #functional #component
ADD COMMENT
Topic
Name
6+3 =