javascriptmaterial-uimaterial-table

How to reset vertical scroll bar position in Material-Table when pagination is triggered?


When I scroll up or down in my Material-Table, and then change page, the vertical scroll bar is not reset to the top of the table. Instead the scroll bar remains where it was before changing page. This is causing some confusion with people who are using the table.

The only scroll bar related props in the documentation for Material-Table is doubleHorizontalScroll, which forces the tables horizontal scroll bar to double in size.

Is there any way to reset the vertical scroll bar when the page is changed?

This is my table:

<MaterialTable
    data={data}
    columns={columns}
    icons={tableIcons}
    options={{
        columnsButton: true,
        pageSize: 25,
        pageSizeOptions: [5, 10, 15, 25, 50, 100],
        padding: "dense",
        filtering: true,
        doubleHorizontalScroll: true,
        maxBodyHeight: "45rem",
        searchFieldStyle: {...},
        headerStyle: {...},
        rowStyle: (data, index) => {...},
    }}
    // I tried using this from a previous question but it results in an error.
    // onChangePage={() => {
        // tableRef.current.tableContainerDiv.current.scroll(0, 0);
    // }}
    actions={[...]}
    components={{
        Toolbar: (props) => <CustomToolbarComponent {...props} />,
    }}
/>

Edit elated-sinoussi-y29trc


Solution

  • The following fixed this issue for me.

    import React, { useRef } from "react";
    
    const tableRef = useRef();
    ...
    <MaterialTable
        tableRef={tableRef}
        data={data}
        columns={columns}
        icons={tableIcons}
        options={{
            columnsButton: true,
            pageSize: 25,
            pageSizeOptions: [5, 10, 15, 25, 50, 100],
            padding: "dense",
            filtering: true,
            doubleHorizontalScroll: true,
            maxBodyHeight: "45rem",
            searchFieldStyle: {...},
            headerStyle: {...},
            rowStyle: (data, index) => {...},
        }}
        onChangePage={() => {
            tableRef.current.tableContainerDiv.current.scroll(0, 0);
        }}
        actions={[...]}
        components={{
            Toolbar: (props) => <CustomToolbarComponent {...props} />,
        }}
    />