Tuesday, August 20, 2019

ReactJs Material UI Table Infinite Scroll

Hello,

Recently in one of my ReactJs project, I faced a challenge in implementing infinite scroll in Material UI table. In this blog I am going to mention trick I have used.

First of all I was really surprised to see that Material UI table does not have infinite scroll function out of the box. It's very much needed. Sometimes something can not be achieved with frameworks, can be achieved via basics of JavaScript. In this I have done something similar.

I tried adding on scroll events on Table, Table Body but it didn't work. I also tried adding refs to body and then bind the Scroll event but that also did not work. After struggling for couple of hours, I finally decided to it with Pure JavaScript.

Step 1 : Wrap material UI table inside the container with fixed height and set overflow = scroll to container.


import styled from "styled-components";

export const Table = props => (
  <TableWrapper id={props.id}>
    <MuiTable {...props}/>
  </TableWrapper>

);

const TableWrapper = styled.div`
  max-height: 500px;
  overflow: scroll;

  ::-webkit-scrollbar {
    width: 3px;
    height: 3px;
  }
`;

As you can see I created a wrapper of table and set max height to it. You can make it dynamic as well depending on window height.

Step 2: Import Table to your component

import {
  Table

 } from './components/Table';

return (
          <>         
             <Table id={"tableID"}/>
          </>
        );

Step 3: Bind scroll event to wrapper

let me = this;
document.getElementById('tableID').onscroll = function(event){
   if(this.scrollTop == (this.scrollHeight - this.clientHeight)){
         //User reached bottom of table after scroll
         //Logic to call web services to get next set of data
   }
};

Hope this helps you.

No comments:

Post a Comment