Creating a Sticky Table Header with Dynamic Height in React using Material-UI

I am currently utilizing the Material-UI library in React to present a table on my webpage. My goal is to have a sticky header on the table without specifying a fixed height, allowing it to scroll along with the page. However, the code snippet provided does not achieve this functionality unless a height is set on the TableContainer element.

Link to example

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>
  );
}

Answer №2

Recently, I encountered a similar issue where I needed my table to occupy 100% of the available height. Instead of applying the 100% height directly to the table, I decided to set it on the parent tag. To achieve this, I calculated the parent's height by referencing my table's container. Here is an example implementation:

// 1. Create a reference
const tableContainerRef = useRef(null);

// 2. Calculate and retrieve the parent's height once the ref is populated
const containerMaxHeight = useMemo(() => {
  if (!tableFormRef.current) return null;

  return tableFormRef.current.parentElement.clientHeight;
}, [tableFormRef.current]);

// 3. Set the parent's height as the maxHeight for your table
return (
  <div ref={tableContainerRef}>
    <TableContainer style={{maxHeight: containerMaxHeight}}>
      <Table>
       ...
      </Table>
    </TableContainer>
  </div>
);

Answer №3

It seems that simply replacing 100% with 100vh solves the issue:

export default function MainPage() {
  return (
    <Container style={{ height: "100vh" }}>
      <Content stickyHeader>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selecting the initial and final elements in a list without utilizing pseudo-classes

Currently, I am in the process of designing a custom MUI styled component and I have encountered a challenge. I want to apply extra styles specifically for the first and last child elements. The issue arises because MUI utilizes the emotion styled library, ...

What is causing the network tab requests not to appear in the browser when I am utilizing NextJS SSR?

I'm currently focusing on a React project that utilizes SSR for SEO benefits. Can you explain how NextJS handles SSR? I'm curious about where the requests originate from if not the browser. Appreciate your help! ...

Limit Javascript Regex to accept only one specific possibility and exclude all others

Here are the specific validations I need for my URL: cars : valid cars/ : valid (Accepting any number of '/' after "cars") cars- : invalid cars* : invalid carsp : invalid (Rejecting any character after "cars" except '/') **cars/ne ...

Utilizing a CSS file within a YAML configuration in R Quarto

Is there a way to reference a css file from a yaml file in my R Quarto Book? The css file defines the theme for my Quarto document, and I want all our Quarto docs to have the same appearance. When I directly call the css file, I can customize aspects like ...

Achieving a seamless scrolling effect using CSS

I recently completed the design of a basic website that includes both mobile and desktop versions. However, I am looking to incorporate some animation into the site to enhance its appearance. One specific feature is a "go up" link at the bottom of the mob ...

Leveraging a vacant CSS class to locate specific HTML elements

While browsing through some HTML code, I noticed the use of classes without any CSS styling attached to them. Instead of using id's, they were simply used to group or identify elements for jQuery selectors: html: <div class=someClass> </div ...

Error: Gulp task needs to have a function assigned to it at Gulp.set

Every time I attempt to execute gulp, I encounter the following error. Here is my gulpfile.js: var gulp = require('gulp'), connect = require('gulp-connect-php'), gulpPhpunit = require('gulp-phpunit'); ...

Expressjs route encountering issue with imported database function failing to return a value

Currently, I am in the process of creating a REST API using Expressjs. Initially, all routes were integrated into one main file. However, I have now separated these routes, database connection, and database methods into their individual files. login-db.js ...

Unable to manipulate mesh rotation using React Three Fiber

I am trying to initialize my Plane mesh with an initial rotation vector, but I am encountering an issue where the rotateX prop is not working as expected. <mesh rotateX={1}> <planeGeometry args={[5, 5, 64, 64]} /> <meshStandardMaterial ...

When the parent element has a fixed position, the child element will no longer maintain its floating property

I'm currently working on a fixed navigation panel that sticks in place while scrolling down. Here is the code I have so far: <header> <a class="logo" href="/">Logo_name</a> <nav> <a href="#">Menu_1</a& ...

A guide on immediately invoking a method when a class is initialized in JavaScript

I'm having some trouble with a class I created to handle user information. When I try to add an init() function to the class so that it runs as soon as the class is initialized, I keep getting a SyntaxError. I've tried following the advice from ...

Error: Identical div IDs detected

<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '> <a class="tabheader" style="font-size:large">Data Type</a><br /> <div class="pane">Refine sea ...

Issue with Jquery code on Mac OS Chrome - it's functional on Windows 10 Chrome though!

Upon clicking the image, it should hide and the YouTube video plays automatically. This functionality works perfectly on Windows 10 but is not functioning on Mac OS or iOS. I am seeking assistance in resolving this issue. I do not own a MacBook, but my c ...

Navigating with React Router v4 using NavLink to highlight the active route

Currently, I am in the process of transitioning my project from utilizing v3 of react-router to v4 now referred to as react-router-dom. The issue stems from having a MenuBar component that is completely independent of the routing logic. In the previous ver ...

Steps for including a path to a base64 encoded image

I am currently facing a challenge in embedding images into my emails where I need to encode them using an online tool. The issue I am encountering is that the email template I am using has a dynamic URL, with ${loginurl}/images as the path to my image. H ...

Is there a substitute for bootstrap select in Rails?

In order to style select tags with Bootstrap, we had to utilize the gem: bootstrap-select However, due to the high volume of options in our data-heavy application, the select dropdowns are causing significant slowdown (loading times, drop down performance ...

Ways to trigger the React component to refresh when it receives an update via a web socket

Looking to enhance a React JS page featuring a dynamic table. Here are the key requirements: Utilize React Table to load and populate the table data by calling the Data API Establish a web socket connection on the client side to receive real-time updates ...

Styling using CSS is effective only when applied locally, as it does not function properly on GitHub Pages

Although I have come across similar questions to the one I am facing, none of the solutions provided seem to work for me at the moment. My CSS file loads and functions as expected when tested locally, but once I upload it to GitHub, it stops working. In my ...

Exploring Nested Views in a MEAN Application using UI Router

I am currently developing a MEAN application and struggling to get my ui-router functioning correctly. Within my index.html template, I have loaded all the necessary javascript and css for my application such as angular, jquery, angular-ui-x, bootstrap. I ...

When using console.log in Node.js, an empty object may be displayed as the

I'm intrigued by the way Node.js displays objects when using console.log(object). In the file constructor.js, I found the following code snippet (taken from the book Learning Javascript Design Patterns): var defineProp = function(obj, key, value){ ...