javascriptreactjsmaterial-table

Material-Table scroll bar does not reset on table page change


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 confusion with people who are using my table.

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

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

This is the 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) => {...},
    }}
    onChangePage={() => {
        tableRef.current.tableContainerDiv.current.scroll(0, 0); // this is the key!
    }}
    actions={[...]}
    components={{
        Toolbar: (props) => <CustomToolbarComponent {...props} />,
    }}
/>

Edit elated-sinoussi-y29trc


Solution

  • I've discovered you may use a combination of tableRef and the onChangePage handler to do it:

    import React, { useRef } from 'react';
    
    function MyComponent() {
      const tableRef = useRef();
      
      const columns = []; // your columns
    
      return (
        <MaterialTable
          tableRef={tableRef} // <-- associate tableRef with MaterialTable
          columns={columns}
          data={[]}
          title="My Title"
          options={{ maxBodyHeight: '70vh' }}
          onChangePage={() => {
            tableRef.current.tableContainerDiv.current.scroll(0, 0); // this is the key!
          }}
        />
      );
    }