Asghwor
Asghwor

Reputation: 593

How to make the Material UI's table header sticky in relation to an outer scroll?

I have a page that uses Material UI's table and I need to get the sticky header working when the entire page is scrolled, since the table must be allowed to take as much vertical space as it needs, like in this pure HTML+CSS example.

I couldn't manage to do this with MUI's table, though. How can it be achieved?

demo

Upvotes: 4

Views: 12086

Answers (3)

MohammadHossein
MohammadHossein

Reputation: 96

To achieve the desired result, you can follow these steps:

  1. Set overflowX: 'initial' in your TableContainer component's style

  2. Add stickyHeader props to your Table component

Here's an example:

<TableContainer component={Paper} sx={{ overflowX: 'initial' }}>
  <Table stickyHeader aria-label="customized table" ref={tableRef}>
      {/* ... */}
  </Table>
</TableContainer>

By following these steps, you should achieve the desired result!

Best of luck!

Upvotes: 0

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27395

Related issue


Wanted mui table with sticky header & rotated to -45 degree angle


Below din't work:

Wasted 3 hours to make stickyHeader work

  <Table stickyHeader ...

Below worked:

  1. Apply head1 CSS for TableHead:
  2. Apply rotatedContent1 CSS for TableCell's child (NOTE: child):

Full code is something like below:

const TableStyles = theme => ({
  head1: {
    zIndex: 3,
    position: 'sticky',
    top: '0px',
  },
  rotatedContent1: {
    transform: 'rotate(270deg)',
  }
})

const Component1 = ({ classes }) => {
  return (
    <React.Fragment>
     <Table>
      <TableHead className={classes.head1}>
        <TableCell>
          <div className={classes.rotatedContent1}> header value </div>
        </TableCell>
      </TableHead>
      <TableBody>
       <TableRow>
        <TableCell> value </TableCell>
       </TableRow>
      </TableBody>
     </Table>
    </React.Fragment>
  )
}

export default withStyles(TableStyles)(Component1)

Upvotes: 1

Yasin Br
Yasin Br

Reputation: 1799

Set overflowX to initial on TableContainer

...
          <TableContainer style={{ overflowX: "initial" }}>
...

Read more on this link

Upvotes: 10

Related Questions