Home > Blockchain >  Nextjs scroll to top button, cannot get scroll position
Nextjs scroll to top button, cannot get scroll position

Time:09-16

trying to implement get to top button but it doesn't seem to be working as intented. I think I got the right code and values but my setup isn't correct. I have the following structure, inside my index.tsc I have a Base component with this code

const Base = () => {
  const [showButton, setShowButton] = useState(false);

  const handleScroll = () => {
    if (window.scrollY > 300) {
      setShowButton(true);
    } else {
      setShowButton(false);
    }
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll, true);
    return () => window.removeEventListener('scroll', handleScroll, true);
  });

  // This function will scroll the window to the top
  const scrollToTop = () => {
    window.scrollTo(0, 0);
  };

  return (
    <div className="antialiased text-gray-600 h-screen w-screen flex flex-col overflow-y-auto">

The scrollY returns the height of the device, not the scroll position.

const Index = () => <Base />;

Tried using document.body and using the scrollYOffset and it all returns the same thing

CodePudding user response:

Do check what is actually scrolling in your UI- the window or a component. You have added overflow-y-auto className, most probably its your div component that is scrolling.

Have added a very basic snippet where window is scrolling, try scrolling it.

class App extends React.Component{
 componentDidMount(){
  window.addEventListener("scroll",()=>console.log(window.scrollY))
 }
 render(){
    return(<div>
    {[1,2,3,4,5,6,7,8,9].map(i=>(
      <div style={{height:"200px",borderBottom:"1px solid"}}>{i}</div>
      ))}
    </div>)
  }
}
  


ReactDOM.render(
  <App/>,
  document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

In case its a component scroll:

const handleScroll = (e) => {
  if((e.scrollHeight-(e.scrollTop e.clientHeight))>300){
     setShowButton(true);
    }
  else setShowButton(false);
}
  • Related