Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI: Give TableBody a max height and make it vertically scrollable

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).

enter image description here

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.

like image 833
etayluz Avatar asked Jun 27 '18 17:06

etayluz


1 Answers

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.

like image 59
Freddy Avatar answered Oct 29 '22 14:10

Freddy