[SalesForce] Setting a max height for datatable in LWC

I know when you specify a div with a height around your datatable you get a nice scrollable table:

<div style="height: 300px:">
    <lightning-datatable various-params></lightning-datatable>
</div>

You'll get something like this if the table goes beyond 300px
enter image description here

Where the scroll is inside the table and the headers stay fixed so you can always see them no matter where you are in the scroll.

The issue is when your data does NOT reach 300px in height, you just get a bunch of empty space after your table and it looks awful. I want a table that is only as tall as its contents UNTIL it reaches a max then the scroll bar appears in the data section like in the picture.

But wrapping a <div style="max-height: 300px;"></div> around my datatable did nothing. Is this possible with the datatable? Or an extreme, extreme oversight on Salesforce? Or can it be done by extending the datatable and using a custom datatable at all?

Best Answer

I do think that this is an oversight by Salesforce. There is, however, a way to dynamically control the height of the datatable's container div as described in this thread: How to control the height of datatable dynamically in LWC?

Here is my implementation where I set a container height of 150px when the number of rows in my table is more than 3:

HTML Code

<div style={datatableHeight}>
    <lightning-datatable
        key-field="updateId"
        columns={columns}
        data={data}
        onrowaction={handleRowAction}
    >
    </lightning-datatable>
</div>

JS Code

get datatableHeight() {
    if (this.pendingUpdates.length > 3) {
        return 'height: 150px;';
    } else {
        return '';
    }
}
Related Topic