How to create table with scroll overflow in Material UI v1 (v1-beta currently)? In component demos in MUI documentation there is no such example.
3 Answers
In all of the Table examples, there is a class applied to the div containing the Table that configures horizontal scrolling. It isn't apparent unless you're viewing the documentation with a sufficiently small viewport. (see BasicTable.js):
const styles = theme => ({
paper: {
width: '100%',
marginTop: theme.spacing.unit * 3,
overflowX: 'auto',
},
});
The paper class is applied to the root element:
function BasicTable(props) {
const classes = props.classes;
return (
<Paper className={classes.paper}>
<Table>
...
If you want a vertical scroll, you'll need to specify a height and include considerations for overflow-y. If you want both horizontal and vertical scrolling, you can set overflow and both axes will be configured:
const styles = theme => ({
paper: {
height: 300,
width: '100%',
marginTop: theme.spacing.unit * 3,
overflow: 'auto',
},
});
Note: This will not fix your column headings, because it is applied to the container. This adjustment will apply scrollbars to the entire table - heading, body, footer, etc.
- 7,180
- 1
- 39
- 43
-
16Ken Gregory, Is there any solution to keep the header in place while having the vertical scroll enabled for the body only? – Matx May 06 '18 at 19:11
-
1mui has the stickheader, for ref: https://mui.com/material-ui/react-table/#sticky-header Or you can try the css, position sticky – moon548834 Jun 20 '23 at 01:34
In order to have the table header fixed and scroll just the table body I've come up with this solution.
First I added to each of the table components the component="div" property in order to get rid of the table skeleton completely.
Then I've added to Table, TableHead, TableBody and TableCell the display: block rule to override the material rules.
TableRows will get display: flex.
TableBody will get the desired fixed (max-)height, plus overflow: auto.
Of course by using divs instead of table tags the header and body cells lose the table alignment. In my case I solved this by setting to the first cells a fixed width, same for the first cells in the header and the first cells in body (or you can go for percentages as well) plus a flex-shrink: 0.
The second cells got flex-grow: 1
Note: Material UI v1 used
- 568
- 5
- 12
-
4There's some detail [on github here](https://github.com/mui-org/material-ui/issues/6625#issuecomment-381729555) for fixing header rows using `position: "sticky"` – sophiemachin Dec 12 '18 at 11:42
Use the "stickyHeader" property on table such as <Table stickyHeader>...</Table>
- 4,620
- 6
- 41
- 75
