4

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

1
  • did you ever get an answer for this? Commented Oct 26, 2022 at 18:10

3 Answers 3

10

Set overflowX to initial on TableContainer

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

Read more on this link

Sign up to request clarification or add additional context in comments.

4 Comments

I tried this, but it has the adverse effect of making the contents of the table leak horizontally. When I tried to add overflow: scroll to the outer container, it stopped working again.
@Asghwor you can remove overflow: "auto" from Paper.
I can't, since I need the table to not overflow from the outer container as well.
This works but screws up the horizontal scroll of the table when you resize the window to mobile width.
1

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)

1 Comment

thank you. I was using <TableContainer> as parent of the <Table> and could't make the stickyHeaders work. I remove it and it worked. Incredible.
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.