I have been trying to read the value of scrollY (chrome Version 96.0.4664.45 (Official Build) (64-bit)). But it does not seems to work. Here is my code :
import React from "react";
import{useEffect, useState} from "react"
export default function Test() {
const [offset, setOffset] = useState(0);
const setScroll = () => {
setOffset(window.scrollY);
};
useEffect(() => {
window.addEventListener("scroll", setScroll);
return () => {
window.removeEventListener("scroll", setScroll);
};
}, []);
return (
<div className="App" style={{ height: "1000px" }}>
<h1>Hello CodeSandbox</h1>
<div>{offset}</div>
</div>
);
}
Here is the same code you provided in your question in a snippet (it works). I simply changed the scroll
event target from window
to document
. See the MDN page for the document scroll event: https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event
<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.4/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="react">
const {useEffect, useState} = React;
function Test () {
const [offset, setOffset] = useState(0);
const setScroll = () => setOffset(window.scrollY);
useEffect(() => {
document.addEventListener("scroll", setScroll);
return () => document.removeEventListener("scroll", setScroll);
}, []);
return (
<div style={{ height: "1000px" }}>
<h1>Hello CodeSandbox</h1>
<div style={{ position: 'sticky', top: '1rem' }}>{offset}</div>
</div>
);
}
ReactDOM.render(<Test />, document.getElementById('root'));
</script>