Scrollable Table with Fixed Header using Reactstrap responsive table

Viewed 1188
3 Answers

Use sticky position for the header cells, and make sure with z-index and background that they will be seen above the body cells

React:

...
<Table height="200" bordered className="fixed-header">
...

CSS:

.fixed-header thead th { /* the thead selector is required because there are th elements in the body */
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: white;
}

Note: that solution might cause issue with the borders of the header - they will not be seen on scroll. Possible solutions for that issue are suggested in this question: Table headers position:sticky and border issue

Just set fixed height to the table body and make its overflow, scroll. ie

.table-body {
 height: 600px;
 overflow-x: scroll;
}

You can add this style in the example.js.

const style = {
  table: {
    width: '100%',
    display: 'table',
    borderSpacing: 0,
    borderCollapse: 'separate',
  },
  th: {
    top: 0,
    left: 0,
    zIndex: 2,
    position: 'sticky',
    backgroundColor: '#fff',
  },
};

And then use the style on the Table & th element tag

<Table bordered height="200" style={style.table}>
   <thead>
      <tr>
        <th style={style.th}>#</th>
        <th style={style.th}>First Name</th>
        <th style={style.th}>Last Name</th>
        <th style={style.th}>Username</th>
      </tr>
 </thead>

Here's the working example code on Stackblitz

Check the result

Patterned with MUI V4 Fixed Header

Related