Get scroll position with Reactjs Get scroll position with Reactjs reactjs reactjs

Get scroll position with Reactjs


You can use event listener in react like you will use in other js framework or library.

componentDidMount() {  window.addEventListener('scroll', this.listenToScroll)}componentWillUnmount() {  window.removeEventListener('scroll', this.listenToScroll)}listenToScroll = () => {  const winScroll =    document.body.scrollTop || document.documentElement.scrollTop  const height =    document.documentElement.scrollHeight -    document.documentElement.clientHeight  const scrolled = winScroll / height  this.setState({    theposition: scrolled,  })}


This should work:

this.setState({    post: post,    theposition: window.pageYOffset});


In case you need to keep on track of the scroll position, you can use react hooks to do so, that way it's possible to check the scroll position any time you need it:

import React, { useState, useEffect } from 'react';...// inside component:const [scrollPosition, setScrollPosition] = useState(0);const handleScroll = () => {    const position = window.pageYOffset;    setScrollPosition(position);};useEffect(() => {    window.addEventListener('scroll', handleScroll, { passive: true });    return () => {        window.removeEventListener('scroll', handleScroll);    };}, []);

In this case useEffect will behavior similar to componentDidMount, it will fire once the component has rendered, but also in every render, as Jared Beach commented bellow: "window.addEventListener is smart enough to discard subsequent calls with the same parameters". . Make sure to return the cleanup function, similar to what you'd do in componentWillUnmount.