Auto scroll table up and down in ReactJs

Viewed 394

I have table which has multiple row and is scrollable. I have been trying to add a functionality of automatic vertical scrolling for the table once component loads, so user does not have to scroll manually. Below is the work I have done so far.


    componentDidMount() {
 
      var tableContainer = document.querySelector("tbody");

      function autoScroller(){
          var sTop = tableContainer.scrollTo(top);
          var sDown = tableContainer.scrollHeight - tableContainer.clientHeight;
          tableContainer.animate({scrollTop:sTop < sDown/2 ? sDown : 0}, 4000, autoScroller);
      }
      autoScroller();
   }
    
   render(){

   return(

            <div className="tableContainer">
               <table className="table table-striped table-dark">
                    <thead>
                       <tr>
                        <th>Table Header</th>
                      </tr>
                     </thead>   
                        <tbody>
                          <tr><td>row 1</td></tr>
                          <tr><td>row 2</td></tr> 
                          <tr><td>row 3</td></tr> 
                          <tr><td>row 4</td></tr> 
                          <tr><td>row 5</td></tr> 
                          <tr><td>row 6</td></tr> 
                          <tr><td>row 7</td></tr> 
                          <tr><td>row 8</td></tr>       
                        </tbody> 
                  </table>   
              </div>

   )
   }

And CSS

table thead tr th{

  position: sticky;
  top: 0;
  background-color: gray;
}

.tableContainer {  
  height:20vh ;
  overflow-y: scroll;
  margin-bottom: 15px;

}

0 Answers
Related