How do I keep a Material-UI Table scrollable with a dynamic height?
Asked Answered
M

1

6

I have a problem with a Material-UI Table component and its size and scrollability.

Short:

The Material-UI table component becomes only scrollable, if its parent has a fixed size. If I set the size to fit the parent 100%, it overflows.

Long:

I have a simple WebApp in Reactjs that consists of a header, a body (where the table lives) and a footer. My App component is styled to distribute those three base layout components as follows:

const useStyles = makeStyles((theme) => ({
  root: {
    height: "100vh",
    maxHeight: "100vh",
    display: "grid",
    gridTemplateRows: "auto 1fr auto",
  },
}));

That works just fine. My body component takes up all the available space to fill the full viewport. The component looks as follows:

<div className={classes.root}>
   <Controls /> //just some buttons, arranged in one line
   <Table /> //my table component, which uses pagination
</div>

The table itself uses pagination and mounts with a default of 10 rows per page.

And the CSS for it looks like that:

root: {
    maxHeight: "100%",
    display: "grid",
    gridTemplateRows: "min-content 1fr",
    gap: "25px",
  },

The table component itself looks like this:

<div className={classes.root}>
      {loading ? loadingAlert : <></>}
      <Paper elevation={3} className={classes.tableRoot}>
        <TableContainer className={classes.container}>
          <Table size="small" stickyHeader aria-label="sticky table">
 [...]

The CSS for my Table component looks like that:

const useStyles = makeStyles({
  root: {
    maxHeight: "100%",
  },
  tableRoot: {
    width: "100%",
    maxHeight: "100%",
  },
  container: {
    maxHeight: "100%", <---
  },
  footer: {
    display: "grid",
    gridTemplateColumns: "1fr min-content",
  },
});

When the user changes the displayed rows per page from 10 to 25, the height of the table changes. In that case, I want the table to take up all the free space within body and become scrollable. If I set the maxHeight of container to a fixed pixel-value, the table becomes scrollable and won't overflow. If I leave it like that, the table overflows and user has to scroll to reach the end of the page.

Can anyone tell me how I can set the height for my container to fit its parent 100% without my table overflowing?

Management answered 16/12, 2020 at 14:20 Comment(0)
M
1

if you use a DataGrid of Material UI, you can use a prop called autoHeight

<DataGrid autoHeight {...data} />
<p>more content</p>

you can check more details in this docs

Mcgowan answered 10/8, 2021 at 1:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.