Using Material UI, I want the TableBody of my Table to have a max height of 500px. If there are any rows that cannot fit within the height of the TableBody then the TableBody should vertically scroll while the TableHead locks in place (frozen).
Here is my code:
import React from "react";
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
const data = ["1", "1","1","1","1","1","1","1","1","1","1","1","1","1"];
class Demo extends React.Component {
render() {
return (
<div>
<Table>
<TableHead>
<TableRow style={{ 'backgroundColor': '#f5f5f5', "height": '35px' }}>
<TableCell>Column 1</TableCell>
<TableCell>Column 2</TableCell>
<TableCell></TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map(n => {
return (
<TableRow key={n}>
<TableCell>{n}</TableCell>
<TableCell>{n}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
);
}
}
export default Demo;
Working example: https://codesandbox.io/s/y03vmkkkqj
How can this be done in Material UI?
Please fork from my example and provide link to a working solution.
You can use stickyHeader
prop in Table
component and give maxHeight
to TableContainer
.
<TableContainer style={{ maxHeight: 150 }}>
<Table stickyHeader>
<TableHead>
<TableRow style={{ 'backgroundColor': '#f5f5f5', "height": '35px' }}>
<TableCell>Column 1</TableCell>
<TableCell>Column 2</TableCell>
<TableCell></TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map(n => {
return (
<TableRow key={n}>
<TableCell>{n}</TableCell>
<TableCell>{n}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
Here is the official demo from material-ui docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With