blazor-webassemblymudblazor

Scroll MudTable to make selected item visible


I have a Blazor WASM application using a MudTable that displays many rows from List<T>.

The MudTable uses @ref="_mappingTable" to identify the table in code.

In code, I set the selected item:

_mappingTable.SetSelectedItem(specificItemFromTheList);
StateHasChanged();

This seems to work fine. However, I'd then like the table to automatically scroll so that item is now visible. It's not automatically doing that and not sure how to achieve that.


Solution

  • There is an open issue requesting a new function "Scroll to row in MudTable" https://github.com/MudBlazor/MudBlazor/issues/5445

    You can wait for that issue to be solved or try the alternative posted by the user geometrikal

    Currently using this code to scroll a row into view. It assumes the table rows are all the same height.

    export function scrollMudTableToRow(rowIndex) {
        var tableElement = document.querySelector("div.mud-table-container");
        var tableHeight = tableElement.offsetHeight;
        var tableOffset = tableElement.scrollTop;
        var tableRowHeight = tableElement.querySelector("tr.mud-table-row").scrollHeight;
    
        // Element is above view - scroll so it is at top
        if (rowIndex * tableRowHeight < tableOffset) {
            tableElement.scrollTo(0, rowIndex * tableRowHeight);
        }
        // Element is below view - scroll so that it is at bottom
        else if ((rowIndex + 1) * tableRowHeight > tableOffset + tableHeight) {
            tableElement.scrollTo(0, (rowIndex + 1) * tableRowHeight - tableHeight);
        }    
    }