Extelliqent
Extelliqent

Reputation: 1858

How to get height of an element at each page update

I have a content area on my page that displays data that gets to be pulled through from an API. I hooked it up so once data gets pulled from the API, it gets saved to the Redux store and page displays it. Now, I need to add a scroll to top and bottom buttons so if page is longer than given amount lets say 600px, they will appear. Odd thing is that, at first load of the page, API query does not kick in therefore page is empty so buttons should not appear.

Given all this, I don't see a way but to do this within componentDidUpdate()

componentDidUpdate() {
    let ContentArea = document.getElementById('contentArea');        
    if(ContentArea != null & ContentArea.clientHeight > 0){
        this.props.pageContentHeight(ContentArea.clientHeight)
    }
}

and save the height value to Redux store so in the code I can display the scrolls like this:

{(contentHeight > 600) && <Scroll to="bottom" /> }
<Router page={pageURL} />
{(contentHeight > 600) && <Scroll to="top" /> }

contentHeight above is coming from redux store.

From what I read, it's not recommended to dispatch within React update lifecycle especially since dispatch causes update lifecycle to kick in too, it might cause a endless cycle. Is there any way I can accomplish that you guys think of adding scroll to top or bottom buttons onto page?

There's this package allows scrolling bottom but not top: https://www.npmjs.com/package/react-scroll-to-bottom

Upvotes: 0

Views: 160

Answers (2)

Extelliqent
Extelliqent

Reputation: 1858

Thank you for @pgsandstrom for his help on the topic.

For anyone trying to implement Scrollbar for content area, I've actually set up Redux to work using componentDidUpdate but then, found out even better approach. What if we can check body height and window inner height and compare then decide based on that? so below code exactly does that. Essentially returns true if scrollbar is visible on the page and false if not, then you can decide to display Scrollbar based on that.

document.body.scrollHeight > document.body.clientHeight

I did below:

componentDidUpdate() {
      if(document.body.clientHeight > window.innerHeight) {
          document.getElementById("topPage").style.display = "block";
          document.getElementById("bottomPage").style.display = "block";
      } else {
          document.getElementById("topPage").style.display = "none";
          document.getElementById("bottomPage").style.display = "none";
      }
  }

make sure to place it inside a component that can recognize the update.

Upvotes: 0

pgsandstrom
pgsandstrom

Reputation: 14399

It is perfectly okay to dispatching actions from life cycles. Just make sure to add guards to avoid infinite loops. That is, only dispatch an action from componentDidUpdate if the data needs to be updated.

Upvotes: 1

Related Questions