简体   繁体   中英

React Material-Ui Sticky Table Header with Dynamic Height

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

import React from "react";
import {
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableCell
} from "@material-ui/core";
import "./styles.css";

export default function App() {
  return (
    <TableContainer>
      <Table stickyHeader>
        <TableHead>
          <TableRow>
            <TableCell>Value</TableCell>
          </TableRow>
        </TableHead>
        {
          Array(100).fill("Test").map((e) => <TableRow><TableCell>{e}</TableCell></TableRow>)
        }
      </Table>
    </TableContainer>
  );
}

Get rid of the TableContainer overflow-x: auto and it should work

const useStyles = makeStyles({
  customTableContainer: {
    overflowX: "initial"
  }
})

export default function App() {
  const classes = useStyles();
  return (
    <TableContainer classes={{root: classes.customTableContainer}}>
      <Table stickyHeader>
      
      ...

编辑cool-shadow-59lrh

Reference: https://css-tricks.com/dealing-with-overflow-and-position-sticky/

Actually I was facing something similar, I wanted my table to be 100% of the available height, so I gave 100% height to the parent tag instead of the table, then in my table a made the calc of the parents height with my table's container reference, the implementation would be something like this

 // 1. create a ref const tableContainerRef = useRef(null); // 2. wait until the container ref is populated and retrieve the parents height const containerMaxHeight = useMemo(() => { if (!tableFormRef.current) return null; return tableFormRef.current.parentElement.clientHeight; }, [tableFormRef.current]); // 3. use the height of the parent as your table's maxHeight return ( <div ref={tableContainerRef}> <TableContainer style={{maxHeight: containerMaxHeight}}> <Table> ... </Table> </TableContainer> </div> );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM