Elevate your Material UI experience by setting a maximum height for TableBody and enabling vertical scrolling for a seamless

I'm looking to utilize Material UI to set a maximum height of 500px for the TableBody within my Table. If there are rows that exceed this height, I want the TableBody to scroll vertically while keeping the TableHead fixed in place.

https://i.sstatic.net/TRHJB.png

Below is the code snippet:

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;

Here's a live demo: https://codesandbox.io/s/y03vmkkkqj

Can you help me achieve this functionality using Material UI? Don't forget to fork from my example and share a link to your solution.

Answer №1

To implement a sticky header in the Table component, use the stickyHeader prop and apply a maxHeight to the 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>

For more information, check out the official demo from material-ui documentation.

Answer №2

To achieve a scrolling body, I had to separate the table head from the main table. The solution required some CSS adjustments to make the body scrollable.

If you're interested, here's the link to view the code: https://codesandbox.io/s/8kw39m1278

Answer №3

To make the table scrollable, I set the max-height for its parent div. However, for the fixed table header, there may be styling issues related to the material-ui that I haven't fully investigated yet. You can explore this further at the following links:

Fixed headers: https://codepen.io/tjvantoll/pen/JEKIu,

CodeSandBox: https://codesandbox.io/s/x92qwnko

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

How to create a dropdown menu in React js with an array of items

Can we structure the array without splitting it into two parts and iterating over them? arrayList=[Jeans, Jackets, Pants, Fragrance, Sunglasses, Health Products] <div className='Flexbox'> //arrayList1.map](//arrayList1.map)(x=>return(< ...

Resizing images in different web browsers: Chrome, IE, and Safari

I'm currently in the process of building a website that utilizes the jquery tabs api. Each tab on the site contains an image that I would like to resize dynamically as the browser window size changes. Here is an example of one of the tabs: <li st ...

Navigating the source-map-explorer tool in a ReactJs environment has left me feeling perplexed

I am facing an issue with my React project where the production build size of the main.xxxx.js file is too large (19.3 MB) and I need to reduce it. After researching online, I found out that analyzing the build files is the first step to identify the code ...

The image is now visible on the screen when utilizing the Material UI <Image> properties

I recently added the mui-image package to my React project and incorporated it as a component using <Image>. However, I encountered an issue where my PNG image (as well as SVG images) did not appear on the screen. Strangely, when I used a random inte ...

The website showcases mobile responsiveness; however, it does not translate to mobile devices

Hello Stockoverflow Community, Recently, I encountered an issue with the responsiveness of my website: The design on desktop appears as: [deleted] However, the mobile version displays as: [deleted] I have already tried clearing my cache, both on Cloudf ...

Implement a function to delete an item from an array within a React object by utilizing the UseState hook

I am facing a challenge in React as I attempt to remove an element from an array within an array of objects using the UseState hook. Despite my efforts, the interface does not re-render and the object remains in place. From what I understand, in order for ...

Enabling scrolling for a designated section of the website

Example Link to Plunker <clr-main-container> <div class="content-container"> <div class="content-area"> <div class="row"> <div class="col-xs-9" style="height:100%; border-right: 1px solid rgb(204, 204, 204); padding-ri ...

Struggling to make addClass and removeClass function correctly for the development of the unique "15 puzzle" game

I am currently in the process of creating a version of "the 15 game" using jQuery in HTML. You can find more information about the game on this page. The objective of the game is to rearrange a table of "boxes" in ascending order from 1 to 15. Below is th ...

Script tag in NextJS

After numerous attempts, I am still struggling with a specific task on this website. The challenge is to insert a script tag that will embed a contact form and newsletter sign-up form, among others, on specific pages of the site. For instance, the contact ...

How to change the border color of a Bootstrap card when hovered over

I'm struggling to achieve a border color change effect on hover for Bootstrap cards. <b-card no-body class="my-card border"> <button>Click here</button> <b-collapse> <b-card-body> <b-c ...

Using a JavaScript variable to control multiple CSS classes

Is there a way to assign multiple CSS classes to an HTML element, including one regular class and one or more JavaScript variables as classes? I attempted to do this by adding it in as a typical script: <div class="style-a <script type="text/javasc ...

When using React.js with Leaflet, ensure that the useEffect hook is only run on Mount when in the

I have encountered an issue where I need to ensure that the useEffect Hook in React runs only once. This is mainly because I am initializing a leaflet.js map that should not be initialized more than once. However, anytime I make changes to the component&a ...

Retrieving the parent value in React-select grouped options

When using react-select with grouped options, the structure is as follows: { label: PARENT_NAME, value: PARENT_ID, options: [ { label: CHILD_NAME, value: CHILD_ID, } ] } An array of these options is passed to the component lik ...

Tips for preventing my text from disappearing off the screen when I resize it

Hello there and thanks in advance. I've recently delved into the world of HTML and CSS and I'm currently in the process of building my own website. I've encountered an issue with a div container where I'm utilizing Bootstrap elements. T ...

Solving the issue of unnecessary white space when printing from Chrome

Whenever I print from Chrome, there seems to be extra space between lines in the middle of a paragraph! Here is an image showing the difference between print emulation and print preview This excess space is always in the same position on various pages an ...

What is the best way to ensure components are on separate lines when enclosed within a <Box> element?

I have grouped all my elements inside a <Box> element and I want to move the submit button away from the three text fields. I attempted to use a <br /> tag but it didn't achieve the desired separation. Visit the website Below is the code ...

Focusing in on a PARTICULAR SECTION of the picture

My website has a unique concept - comparing two articles side by side. One of the articles is mine, while the other is displayed alongside it. To capture entire pages for comparison, I utilize Google's GoFullPage feature to take screenshots. The goa ...

Scaling boxes responsively according to screen size utilizing Bootstrap

Creating a portfolio website with a carousel section to display completed projects in a 2x2 grid layout, transitioning to a 1x4 on smaller screens is proving to be quite challenging. After trying various methods from Bootstrap documentation and YouTube tut ...

The alternative text for the oversized image exceeds the boundaries

After setting the width and height for an image, along with testing overflow:hidden, I've encountered an issue where the alt text for a broken image overflows the bounds of the image and the image size is lost. How can I contain the alt text within th ...

Tips on verifying if a user accesses a legitimate route while utilizing Nextjs

I've been searching for a solution to my question for the past 2 hours online with no luck. I'm currently using Nextjs with the new App router and I'm facing an issue when a user navigates to an undefined route in app/api. For example: ( ...