1

I am working on a dashboard part of a site and i am very new to reactjs. I am trying fit everything on a screen so that the user does not have to scroll expect for the table, i hope the code below defines the situation better.

Here is my code:

componentDidMount() {
    this.tableHeightOffset();
}

tableHeightOffset() {
    var getOffset = this.containerLine.offsetTop;
    this.setState({ getOffset });
}

render() {

    var findTableHeight = this.state.getOffset;
    const tableHeight = {
      height: 'calc(100vh - ' + findTableHeight + 'px' + ')'
    }

    return (
        <div className="table-responsive" style={tableHeight} ref={el => this.containerLine = el}>
    )
}

How do i get the offset to change when the browser resize or there is a update on the site ?

Also I get the value on findTableHeight but it is not getting the offset from to the top of the window. I was suppose to get 161px of offsetTop but i am only getting 46px.

umanga shrestha
  • 368
  • 2
  • 8
  • 29

2 Answers2

2

You could define a resize listener to the window, in order to calculate the new hight. This could be done in componentDidMount():

componentDidMount() {
  window.addEventListener('resize', this.tableHeightOffset);
}

Don't forget to remove it before unmounting the component:

componentWillUnmount() {
  window.removeEventListener('resize', this.tableHeightOffset);
}

Also offsetTop returns the offset from the parent. In order to find the offset relative to the document, check this article: Finding element's position relative to the document

Enchew
  • 981
  • 5
  • 11
  • I get "TypeError: Cannot read property 'offsetTop' of undefined" when resizing the screen. I am not sure what's the reason behind this. – umanga shrestha Mar 04 '20 at 17:19
  • Try defining the ref in the constructor: constructor() { super(); this.containerLiner = React.createRef(); } And after:
    – Enchew Mar 05 '20 at 08:09
0

Here you have api to listen for window size change https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event use it to dynamically change your offset.