reactjsreact-bootstrap-table

How to programmatically set the height of a BootstrapTable element?


I need to programmatically set the height of a BootstrapTable element (because I want to ensure that the table takes the available space up to the bottom of the browser window). I tried to set the CSS property height of the div with the CSS class react-bs-table (that's where the height would go if I set it in the height attribute of the BootstrapTable element). Looks like this:

componentDidMount() {
   // Calculate the height
   let height = 200; // Only simluated here!

   // Set the height
   const tableElement = document.getElementsByClassName('react-bs-table')[0];
   tableElement.style.height = height + 'px';
}

Problem with this approach is that the data rows of the BootstrapTable overflow it's bottom border. Seems like the height of this overflow is the height of the header.

Fiddle

How can I set the height of a BootstrapTable correctly (without the data rows overflowing the element)?


Solution

  • You should use the maxHeight prop (not height) of <BootstrapTable> to set the height, rather than modifying the DOM element.

    Have a look at the official docs:

    Use maxHeight to set the maximum height of table. You need give a string with an unit(px) value like height:

    Just do the following changes:

    componentDidMount() {
      let height = 200;
      this.setState({tableHeight: height + "px"});
    }
    
    render() {
      ...
      <BootstrapTable maxHeight={this.state.tableHeight} id="table" data={this.state.products} striped hover>
      ...
    }
    

    You might want to initialize this.state.tableHeight in your constructor as well...

    jsfiddle


    If you still want to update the styling the way you do it, directly through the DOM and not with React (though discouraged), you can do:

    componentDidMount() {
      let height = 200;
      const tableElement = document.getElementsByClassName('react-bs-container-body')[0];
      tableElement.style.maxHeight = height + 'px';
    }
    

    Note that I used react-bs-container-body and not react-bs-table.

    jsfiddle