Detect bottom of page to fetch more data in react
Put this in your componentWillMount()
window.addEventListener('scroll', function() { if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { console.log("you're at the bottom of the page"); // Show loading spinner and make fetch request to api }});
Don't forget to kill your event Listeners in componentWillUnmount()
to prevent memory leaks.
constructor(props) { super(props); this.state = { height: window.innerHeight, message: 'not at bottom' }; this.handleScroll = this.handleScroll.bind(this);}handleScroll() { const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight; const body = document.body; const html = document.documentElement; const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); const windowBottom = windowHeight + window.pageYOffset; if (windowBottom >= docHeight) { this.setState({ message: 'bottom reached' }); } else { this.setState({ message: 'not at bottom' }); }}componentDidMount() { window.addEventListener("scroll", this.handleScroll);}componentWillUnmount() { window.removeEventListener("scroll", this.handleScroll);}
Edited please note this is a react hook solution
useEffect(() => { const scrolling_function = () => { if((window.innerHeight + window.scrollY) >= document.body.offsetHeight-10){ console.log("fetching more.........") window.removeEventListener('scroll',scrolling_function) } } window.addEventListener('scroll', scrolling_function); }, [target_data])