I am using the Material-UI framework for React to display a table. I would like to use a sticky header; however, I do not want to set a height on my table, as I’d like it to scroll with the page. The following snippet does not stick the header unless I set a height on the TableContainer.
https://codesandbox.io/s/winter-firefly-5wlx2?file=/src/App.js
JavaScript
x
27
27
1
import React from "react";
2
import {
3
TableContainer,
4
Table,
5
TableHead,
6
TableRow,
7
TableCell
8
} from "@material-ui/core";
9
import "./styles.css";
10
11
export default function App() {
12
return (
13
<TableContainer>
14
<Table stickyHeader>
15
<TableHead>
16
<TableRow>
17
<TableCell>Value</TableCell>
18
</TableRow>
19
</TableHead>
20
{
21
Array(100).fill("Test").map((e) => <TableRow><TableCell>{e}</TableCell></TableRow>)
22
}
23
</Table>
24
</TableContainer>
25
);
26
}
27
Advertisement
Answer
Get rid of the TableContainer
overflow-x: auto
and it should work
JavaScript
1
14
14
1
const useStyles = makeStyles({
2
customTableContainer: {
3
overflowX: "initial"
4
}
5
})
6
7
export default function App() {
8
const classes = useStyles();
9
return (
10
<TableContainer classes={{root: classes.customTableContainer}}>
11
<Table stickyHeader>
12
13
14
Reference: https://css-tricks.com/dealing-with-overflow-and-position-sticky/