DEV Community

MOHSIN ALI SOOMRO
MOHSIN ALI SOOMRO

Posted on

Track Scroll event in reactjs

Code...

 import { useState } from "react";
import "./styles.css";

export default function App() {
  const [scroll, setScroll] = useState(0);
  const onScroll = () => {
    const scrollY = window?.scrollY;
    const scrollTop = document.getElementById("test").scrollTop;

    setScroll(scrollTop);
  };
  return (
    <div className="App">
      <h1>Scroll Position {scroll}</h1>
      <div
        id="test"
        onScroll={onScroll}
        style={{
          backgroundColor: "white",
          zIndex: "100",
          height: "200px",
          overflowY: "scroll"
        }}
      >
        content...
      </div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Codesandbox

Top comments (0)