A guide on implementing a Material UI table to display one row at a time on each page

I'm currently working on incorporating a Material UI table to showcase content with just one row per page.

After successfully loading the page and displaying the first row, I encountered an issue where navigating to subsequent pages does not render any content.

I am in search of a sample that demonstrates how to utilize the table pagination options effectively for displaying one row per page.

Here is what I have implemented so far:

import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableFooter from '@material-ui/core/TableFooter';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import IconButton from '@material-ui/core/IconButton';
import FirstPageIcon from '@material-ui/icons/FirstPage';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
import LastPageIcon from '@material-ui/icons/LastPage';
import './styles.css';

const useStyles1 = makeStyles((theme) => ({
  root: {
    flexShrink: 0,
    marginLeft: theme.spacing(2.5),
  },
}));

function TablePaginationActions(props) {
  const classes = useStyles1();
  const theme = useTheme();
  const { count, page, rowsPerPage, onChangePage } = props;

  const handleFirstPageButtonClick = (event) => {
    onChangePage(event, 0);
  };

  const handleBackButtonClick = (event) => {
    onChangePage(event, page - 1);
  };

  const handleNextButtonClick = (event) => {
    onChangePage(event, page + 1);
  };

  const handleLastPageButtonClick = (event) => {
    onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
  };

  return (
    <div className={classes.root}>
      <IconButton
        onClick={handleFirstPageButtonClick}
        disabled={page === 0}
        aria-label="first page"
      >
        {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
      </IconButton>
      <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page">
        {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
      </IconButton>
      <IconButton
        onClick={handleNextButtonClick}
        disabled={page >= Math.ceil(count / rowsPerPage) - 1}
        aria-label="next page"
      >
        {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
      </IconButton>
      <IconButton
        onClick={handleLastPageButtonClick}
        disabled={page >= Math.ceil(count / rowsPerPage) - 1}
        aria-label="last page"
      >
        {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
      </IconButton>
    </div>
  );
}

TablePaginationActions.propTypes = {
  count: PropTypes.number.isRequired,
  onChangePage: PropTypes.func.isRequired,
  page: PropTypes.number.isRequired,
  
};

function createData(number, icon, heading, explanation) {
  return { number, icon, heading, explanation };
}

const rows = [
    createData(1, 'Cupcake', 305, 3.7),
    createData(2, 'Donut', 452, 25.0),
    createData(3, 'Eclair', 262, 16.0),
    
  ].sort((a, b) => (a.number < b.number ? -1 : 1));
  
const useStyles2 = makeStyles({
  table: {
    // minWidth: 500,
  },
});

export default function CustomPaginationActionsTable() {
  const classes = useStyles2();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(1);

//   const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };


  return (
    <TableContainer component={Paper}>
      <Table className={classes.table} aria-label="The design studio supports research">
        <TableBody>
          {(rowsPerPage > 0
            ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
            : rows
          ).map((row) => (
            <TableRow key={row.number}>
              <TableCell  align="right">
                {row.icon}
              </TableCell>
              <TableCell component="th" scope="row" style={{ width: "80%" }}>
                {row.heading}
                {row.explanation}
              </TableCell>
              
              
            </TableRow>
          ))}

          
        </TableBody>
        <TableFooter>
          <TableRow>
                <TablePagination
                colSpan={3}
                
                rowsPerPage={rowsPerPage}
                rowsPerPageOptions={[1]} 
                onChangePage={handleChangePage}
                
                ActionsComponent={TablePaginationActions}
                />
          </TableRow>
          </TableFooter>
          </Table>
    </TableContainer>
  );
}

The first page renders as follows:

The second page displays:

To resolve the issue of not being able to display row content on subsequent pages, any suggestions or solutions would be greatly appreciated.

Answer №1

It seems like the issue you're facing is related to the changes in the page structure. When I tested your code, I consistently received NaN for the pages. This inconsistency might be disrupting your code since you're using slicing, but slicing values that don't actually exist, causing issues with additional row cutting. As a result, your code functions correctly only on the first page and not on any subsequent pages.

You may want to consider looking into this thread for further information:

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

I'm experimenting with crafting a new color scheme using MUI, which will dynamically alter the background color of my card based on the API

I am attempting to create a function that will change the colors based on the type of Pokemon. However, I'm not sure how to go about it. Any suggestions or ideas!? Check out where I'm brainstorming this logic [This is where the color palette sh ...

Tips for choosing a sibling element on hover using CSS

I'm having trouble figuring out how to make the rect element change color to purple when the text is highlighted. Right now, only the text color is changing. Is there a way to achieve this using just CSS? The goal is for the rect to turn purple on ho ...

Style.css remains invisible to NetBeans

My webapp is built using Servlets and JSP. However, I am currently facing an issue with directing NetBeans to my style.css file. Whenever the stylesheet is placed in WEB-INF or META-INF or even outside them within the Web Pages directory, everything func ...

Is it wise to use the<sup>attribute for mandatory form fields?

Would it be wise to utilize the <sup> tag instead of using margin-top: -xnumberofpx for indicating required fields in a form? <label for="address1" required>Address line 1<sup><img src="/src/images/requiredAsterix.png" width="10" heig ...

Enhance Your Highcharts Funnel Presentation with Customized Labels

I am working on creating a guest return funnel that will display the number of guests and the percentage of prior visits for three categories of consumers: 1 Visit, 2 Visits, and 3+ Visits. $(function () { var dataEx = [ ['1 Vis ...

Pictures glide within containers

Hey, I'm having an issue with my images. They're not floating like they should be, even though they are centered in the div. I really want them to float and be centered. Here's the code snippet I've been working with. HTML <div cla ...

Adjust the size of the <textarea> to match the height of the table cell

Below is the code I am using to generate a table containing an image along with a <textarea>: <table border="1" style="border-color: #a6a6a6" cellpadding="4" cellspacing="0" width="702">\ <col width="455"> <col width="230"> ...

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

Certain Material-UI components appear to lack proper styling

I found a tutorial on how to incorporate material UI into my app at this link: https://mui.com/material-ui/getting-started However, I noticed that some components are not styled as expected and customizing the theme seems to have no effect... This is how ...

If the navigation menu contains sub-menus, it should slide to the left

I am currently working on developing a navigation menu with four levels of depth. The menu displays three levels at a time, and when the user reaches the fourth level, the first level should move to the left to make room for the second, third, and fourth l ...

Is there a way to decrease the padding within the table cells when using material-react-table?

How can I adjust the padding in table cells with class names such as: MuiTableCell-root MuiTableCell-body MuiTableCell-sizeMedium css-ny9njj-MuiTableCell-root I am currently using version 1.14.0 of material-react-table. I have searched the documentation b ...

Display a text over a full-screen HTML5 video

Is there a way to display text on a fullscreen video in HTML? I have tried using absolute positioning for the text and relative/fixed/none positioning for the video, but it does not work when the video is in fullscreen mode. I also attempted to call the ...

The Bootstrap dropdown menu is cut off and not fully visible on mobile devices

I am experiencing an issue with the mobile version of a website where the dropdown menu is not fully visible due to the position of a specific menu item and the number of items in the dropdown. The image below shows how I would like it to be displayed, fo ...

AngularJs - Show the response only upon verifying the correct answer

Let me provide an overview of what has been implemented so far: When a user selects an answer in radio buttons and clicks on "Check Answer", the system displays either "Correct" (in green) or "Incorrect" (in red) in the first answer field. Additionally, th ...

How to customize a disabled paper-input element in Polymer 1.0?

Help with Polymer 1.0: I've encountered an issue where setting a paper-input element to 'disabled' results in very light gray text and underline, making it hard to read. I've been trying to use CSS to change the text color but haven&ap ...

implement adding a division element to the DOM using the append

I am facing an issue with this particular code. The intended functionality is to create multiple divs in a loop, but it seems to be dysfunctional at the moment. Upon clicking, only one div appears and subsequent clicks don't trigger any response. < ...

Automatically scrolling down a div as new content is added using XMLHTTPRequest.openConnection

https://jsfiddle.net/kv5gbamg/ - I created a jsfiddle to demonstrate the functionality of the system Essentially, I am seeking a way to automatically scroll the scrollbar to the bottom every time a new message is received. My system updates the div with ...

The module cannot be located due to an error: Package path ./dist/style.css is not being exported from the package

I am facing an issue with importing CSS from a public library built with Vite. When I try to import the CSS using: import 'rd-component/dist/style.css'; I encounter an error during the project build process: ERROR in ./src/page/photo/gen/GenPhot ...

Don't forget to keep track of when the user has closed

How can I ensure that the cache retains the user's action of closing the div? Currently, when I close the div and refresh the page, it reverts back to its original state. Is there a way to make this change persistent? Experience it live: Here is the ...

Experiencing inconsistencies with CSS on certain devices?

When faced with a research issue, I usually turn to Google for answers. However, this time, I was unsure of where to begin. As part of my efforts to enhance my frontend development skills, I undertook The Odin Project and worked on a calculator project. U ...