From 38b2d91f181c9b500b0aa068895b51cff41d1415 Mon Sep 17 00:00:00 2001 From: Sonny Bakker Date: Wed, 21 Jul 2021 21:06:46 +0200 Subject: [PATCH] Only show buttons when needed --- .../js/pages/homepage/components/ScrollTop.js | 50 ++++++++++++------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/src/newsreader/js/pages/homepage/components/ScrollTop.js b/src/newsreader/js/pages/homepage/components/ScrollTop.js index 83fdb43..24228b1 100644 --- a/src/newsreader/js/pages/homepage/components/ScrollTop.js +++ b/src/newsreader/js/pages/homepage/components/ScrollTop.js @@ -1,24 +1,40 @@ import React from 'react'; -// TODO show buttons when applicable -// TODO caclulating height needs to take into account react renders later? -const scrollTop = () => { - if (document.body.clientHeight < document.documentElement.clientHeight) { +export default class ScrollTop extends React.Component { + scrollListener = ::this.scrollListener; + + state = { showTop: false, showBottom: false }; + + componentDidMount() { + window.addEventListener('scroll', this.scrollListener); + } + + scrollListener() { + const showBottom = window.innerHeight + window.scrollY < document.body.offsetHeight; + + this.setState({ + showTop: window.pageYOffset > 0 ? true : false, + showBottom: showBottom, + }); + } + + render() { return (
- window.scrollTo(0, 0)} - /> - window.scrollTo(0, document.body.scrollHeight)} - /> + {this.state.showTop && ( + window.scrollTo(0, 0)} + /> + )} + + {this.state.showBottom && ( + window.scrollTo(0, document.body.scrollHeight)} + /> + )}
); } - - return null; -}; - -export default scrollTop; +}