Navigate only within the tbody section of the Material UI Table by scrolling

Utilizing the material-ui Table component to build a table with a sticky header presents a challenge. The default behavior is for the scroll to encompass both the thead and tbody of the table. However, I specifically require the scroll functionality to be limited to the tbody only. This customization is straightforward with a basic HTML table but proves to be more complex with the mui table component. Any guidance or tips on how to achieve this unique requirement would be greatly appreciated.

Dummy Data:

const columns = [
    { id: 'name', label: 'Name', minWidth: 170 },
    { id: 'code', label: 'ISO', minWidth: 100 },
    { id: 'population', label: 'Population' },
    { id: 'size', label: 'Size' }
  ];
  
  const rows = [
    { name: 'India', code: 'IN', population: '1324171354', size: '3287263' },
    { name: 'India', code: 'IN', population: '1324171354', size: '3287263' },
    { name: 'India', code: 'IN', population: '1324171354', size: '3287263' },
    { name: 'India', code: 'IN', population: '1324171354', size: '3287263' },
    { name: 'India', code: 'IN', population: '1324171354', size: '3287263' },
    { name: 'India', code: 'IN', population: '1324171354', size: '3287263' },
    { name: 'India', code: 'IN', population: '1324171354', size: '3287263' }
  ];

Table Component

<TableContainer style={{ maxHeight : 400 }}>
    <Table stickyHeader aria-label="sticky table">
      <TableHead>
        <TableRow>
          {columns.map((column) => (
            <TableCell
              key={column.id}
              align={column.align}
              style={{ minWidth: column.minWidth }}
            >
              {column.label}
            </TableCell>
          ))}
        </TableRow>
      </TableHead>
      <TableBody>
        {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => {
          return (
            <TableRow hover role="checkbox" tabIndex={-1} key={row.code}>
              {columns.map((column) => {
                const value = row[column.id];
                return (
                  <TableCell key={column.id} align={column.align}>
                    {column.format && typeof value === 'number' ? column.format(value) : value}
                  </TableCell>
                );
              })}
            </TableRow>
          );
        })}
      </TableBody>
    </Table>
  </TableContainer>
  <TablePagination
    rowsPerPageOptions={[10, 25, 100]}
    component="div"
    count={rows.length}
    rowsPerPage={rowsPerPage}
    page={page}
    onPageChange={handleChangePage}
    onRowsPerPageChange={handleChangeRowsPerPage}
  />

Answer №1

After some experimentation, I stumbled upon a solution that worked well for me. I wanted to share it here in case anyone else is facing a similar issue.

There is definitely room for improvement in this approach. What I ended up doing was using two separate tables and wrapping the table containing the tbody with a TableContainer.

<Table stickyHeader aria-label="sticky table">
  <TableHead>
    <TableRow>
      {columns.map((column) => (
        <TableCell
          key={column.id}
          align={column.align}
          style={{ minWidth: column.minWidth }}
        >
          {column.label}
        </TableCell>
      ))}
    </TableRow>
  </TableHead>
</Table>
<TableContainer className={classes.container}>
<Table>
  <TableBody>
    {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => {
      return (
        <TableRow hover role="checkbox" tabIndex={-1} key={row.code}>
          {columns.map((column) => {
            const value = row[column.id];
            return (
              <TableCell key={column.id} align={column.align}>
                {column.format && typeof value === 'number' ? column.format(value) : value}
              </TableCell>
            );
          })}
        </TableRow>
      );
    })}
  </TableBody>
</Table>
</TableContainer>

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

What is the best way to display link icons - as images or using CSS background-image URLs?

When designing a web UI, I am considering using iconography to represent actions such as adding, editing, deleting, and searching for items. However, I want to ensure that the purpose of each action is clear without displaying text and cluttering the UI sp ...

Steps to turn off Bootstrap's fixed navigation on mobile devices

When a user visits the mobile version of the website or scales the webpage, the Bootstrap navbar will no longer remain fixed at the top. I am looking to set it as a normally scrolling view in the navbar. The Bootstrap class is "navbar-fixed-top" https:// ...

Profile picture placeholder with conditional logic

After extensively searching online, I was unable to find a solution on how to add a default profile picture. Here is the code snippet I used for uploading an image chosen by the user: <td><img class="image" src="image/<?php echo $contact[&apos ...

Visual feedback: screen flashes upon clicking to add a class with jQuery

I have successfully added a click event to my pricing tables in order to apply an animation class on mobile devices. However, I am facing an issue where every time I click on a pricing option on my iPhone, the screen flashes before the class is applied. Is ...

At what point does the browser begin fetching the background images specified in a stylesheet?

Are images mentioned in a valid CSS declaration with a background-image value downloaded when the stylesheet is parsed or when the declaration is applied on a page? In simpler terms, do I need to download all background images listed in my stylesheet even ...

Avoid automatic background resizing to match the full width of the header text

I've been trying to use CSS to style my <h1> element in a specific way, but it seems the default browser behavior is getting in the way: Despite my efforts, the browser continues to display it like this: Anyone have any suggestions on how I ca ...

Developing Wordpress plugins involving images - path not found

I'm currently developing a WordPress plugin and encountering some issues with images. My plugin is located in wp-content/plugins/my-plugin/ directory, and within that, there's a folder named images/test.png - how can I properly reference this ima ...

React-Troubleshooting list items and keys: A comprehensive guide to resolving common issues

I'm facing a challenge with generating unique key ID's for my list items. Even though I thought I had a good understanding of how unique keys function, it seems that I am mistaken. In the code snippet below, using key={index} or key={item} is no ...

Incorporate a new CSS class into a DIV using JavaScript

Sample HTML: <div id="bar" class="style_one"></div> Is there a way to include the class style_two without deleting style_one? final outcome: <div id="bar" class="style_one style_two"></div> ...

What is the best way to move information from one table to a different one?

I have two tables: users2 and user_totals. Each of these tables has rows named clicks (impression_count), fclicks (use_count), and completed_stus (completion_count). The ones in brackets are the new additions in the user_totals table. I would like to tra ...

Can you explain the distinction between @types/material-ui and the official @mui/types bundle?

When it comes to npm packages, I came across @types/material-ui and @mui/types. I'm aware that the former is backed by the Definitely Typed community, but what's the reasoning behind its existence when an official types package already exists? D ...

Tips for adjusting the height and border of Bootstrap tabs

I'm facing an issue with the modal and nav-tabs I created. There are a couple of problems that need to be addressed. Firstly, the tabs have excessive height and I've tried adjusting it using CSS height property, but it's not working as e ...

Align content vertically within a div container

I have encountered an issue where I am trying to center vertically the content within a div. Here is an example of the structure: <div class="container-fluid"> <div class="row restaurant"> <div class="col-md-6"> & ...

Tips for confirming each form stage in material ui stepper?

This is a typical material-ui stepper displayed below. export default function HorizontalLinearStepper() { const classes = useStyles(); const [activeStep, setActiveStep] = React.useState(0); const [skipped, setSkipped] = React.useState(new ...

The child div can be scrolled horizontally, while the parent window remains fixed

I am facing a challenge with my HTML and CSS setup. I want to create a child div that scrolls horizontally, but I do not want the parent window to scroll along with it. Below is my current code: <div id="parent"> <div id="div1"> . ...

Unable to see the changes made to the Understrap child-theme and the color variable in Sass is not

I am trying to adjust the main theme color assigned by $primary in _theme_variables.scss. I changed the default value from $purple to $orange while using npm run watch-bs (browser-sync). However, the change is not reflecting on the home page: https://i.ss ...

CSS Menu Not Functioning Properly on iPad While Scrolling is Required

My CSS dropdown menu has mouseout and mouseover events but I'm experiencing issues on iPads and iPhones. The menu automatically closes when scrolling, making it difficult to open any links unless the menu is short enough to avoid scrolling. Does anyon ...

What is the reason behind modern browsers continuing to add spaces between inline blocks when there is whitespace present?

Consider the following HTML markup: <div class="inlineblock">one</div> <div class="inlineblock">two</div> <div class="inlineblock">three</div> Accompanied by this CSS style: .inlineblock{ display: inline-block; } ...

`.svg file appearing slightly fuzzy when magnified in Chrome``

After careful consideration, I've chosen to use an SVG for my website logo. However, I am facing an issue with it rendering properly in Google Chrome. When the zoom level is set at 100%, the image appears blurry, but if I zoom out a couple of times, i ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...