Home > front end >  How to re-render component when the scrollHeight of the page changes
How to re-render component when the scrollHeight of the page changes

Time:08-01

I have a component that uses the document.body.scrollHeight to get the total content height of the current page.

here is the code:

class CartModal extends Component {
  state = {
    scrollHeight: document.body.scrollHeight,
  };

  getContentHeight = () => {
    const navHeight = document.getElementById("navigation").clientHeight;
    return this.state.scrollHeight - navHeight;
  };

  render() {
    return createPortal(
      <div
        className={style.cartModal}
        style={{ height: `${this.getContentHeight()}px` }}
      >
        <Modal/>
      </div>,
      document.getElementById("modal")
    );
  }
}

Actually, I want to give an overlay semi-dark background to the whole page when the modal opens. That is why I am calculating the height of the page excluding the navbar.

This works. But the problem is when I change my route the scrollHeight does not change. only when I refresh the page then it changes. Now how can I rerender this component when the user changes the route of the app?

CodePudding user response:

Add the useEffect.

useEffect(() => {
   getContentHeight()
}, [])

CodePudding user response:

Maybe add one useEffect in the component like

useEffect(() => {
   getContentHeight()
}, [])

CodePudding user response:

Actually, after much research, i found my problem solution. I used a resizeObserver API. It continuously checks the document behavior.

componentDidMount() {
    // create an Observer instance
    const resizeObserver = new ResizeObserver((entries) => {
      this.setState({ scrollHeight: entries[0].target.clientHeight });
    });

    // start observing a DOM node
    resizeObserver.observe(document.body);
  }
  • Related