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

In React Material UI, there seems to be an issue where the image and h4 elements are not displaying next

I am currently working with material ui in react. I am facing an issue where the image and h4 elements are aligned vertically instead of being placed adjacent to each other. I have tried adjusting the width, but it doesn't seem to be working. https:/ ...

The dropdown menu in the bootstrap is not being properly filled with content on the webpage

In my header file, I am attempting to add a bootstrap dropdown that will display the user id along with two other options in the dropdown menu. Within the header file, I have created a new div element for the dropdown and linked it to a php file where the ...

Objective subject for an element within a :not operation

I have a function that specifically excludes a style on links by targeting their IDs. Each of my links has an ID, so I use that to exclude the style. a:not([id='hopscotch_logo'] { color: red; } Now, I also want to find links that are children o ...

What's the best way to align divs vertically in a compact layout?

Update The reason I require this specific behavior is to ensure that all my content remains in chronological order, both on the web page and in the HTML structure. This way, even if the layout collapses into a single column on smaller screens, the content ...

Navigating the World of Material-UI Size Options

When exploring the sizing documentation, I came across a statement that said "Easily make an element as wide or as tall (relative to its parent) with the width and height utilities." I couldn't help but notice that most of the examples in the system ...

Enhance your webpage with a stunning background video

I'm trying to add a background video that covers the entire screen but maintains a height of 400px, similar to the one shown here. Is there a way to achieve this without using JavaScript? Below is the HTML code I currently have: <div class="pr ...

Alignment issue detected

I was attempting to center these 4 divs inside a container both horizontally and vertically, but they are stuck at the top edge of the <div>. They aren't moving down and remain fixed at the top. /* Footer */ #footer { width: 100%; hei ...

Creating a dynamic 2x2 grid with centered responsiveness in Angular Ionic framework

I'm having trouble achieving a 2 x 2 grid that is centered on my screen. The code snippet below shows what I have so far in the HTML file. Just to provide some context, this project is meant for a native mobile application. <ion-header> <i ...

Creating a personalized version of Material UI with unique styles, and uploading it to my GitHub repository for universal reuse across all my projects

Seeking input on the best solution for customizing MUI themes in my React projects. Currently, I manually copy theme files from previous projects to maintain consistency in styling between MUI and my UI design. Looking to create a custom library based on M ...

Choose the div element that is immediately before the current div

Attempting to create a harmonica effect by adjusting the height of divs upon hovering over another. The HTML is structured as follows: <html><body> <div class="section1"></div> <div class="section2"></div> <di ...

What steps can I take to troubleshoot and repair my accordion feature within an Angular project?

As a newcomer to Angular, I recently attempted to create an accordion component but encountered unexpected behavior. Here is the HTML code for my attempt: <div class="faq-item-container"> <h1 class="mt-1 mb-5"><strong>Frequently A ...

Dynamic component in React Material UI and React Hook Form for a clear button functionality

I have a specific requirement to create a unique React TextField component with an additional feature of a clear button. Despite adding the button, the functionality seems to be malfunctioning. Below is the code snippet and description of the Custom Compon ...

Unusual alterations to HTML and CSS to meet specific needs

Struggling with bringing my website ideas to life! My header contains a navigation bar, followed by a centered chat box within a fixed <section>. Want the left and right side of the chat box to be content areas that scroll in sync while the chat box ...

Prevent fixed element from scrolling beyond a specific point

I'm working on a fixed sidebar that needs to scroll along with the main content and stop at a specific point when scrolling down, and vice versa when scrolling up. I've created a script that calculates the window height, current scroll position ...

Webpage with visual representation

Currently in the process of redesigning my university's drama department website, I'm looking to incorporate three images side by side with spacing and captions. The captions need to have a header that's styled differently from the caption i ...

css displaying drop-down menu when hovered over

I've been trying to create a link that, when hovered over, displays a list of options. I've managed to make it work in Firefox and Google Chrome, but it doesn't display at all in Internet Explorer when hovering over the link. I'm also ...

Creating two distinct SVG images without interfering with other div elements can be accomplished by properly structuring the HTML

I am working on a page layout that consists of three main sections. There is a top bar with buttons, a middle section that needs to load different pages using jQuery, and a bottom bar with additional buttons. On top of all this are floating windows that op ...

Position a div in the center both horizontally and vertically within a section, ensuring that each section expands to fill the entire page when scrolling

I'm currently working on coding a page layout where each section takes up the entire screen. My goal is to have the content within each section centered both vertically and horizontally. I'm unsure if this is achievable, so any guidance or advice ...

Slider text in Master not adjusting properly for mobile devices

I am at my wits' end trying different solutions to make this work properly. The text on the slider of my homepage appears jumbled up when viewed on a mobile device. I suspect it might be related to responsive design? Could someone please take a look ...

Combining left-aligned and centered elements within a grid using flexbox

Looking to create a fluid responsive grid layout using flexbox, without the need for media queries. The number of elements in the grid can vary and each item should have a fixed, equal width with left alignment. The entire group should have equal left and ...