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:

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

The second page displays:

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

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

Is there a way to stop text from wrapping between words and punctuation marks using CSS or jQuery?

There is a paragraph containing some text. One issue I am facing is that punctuation at the end of a word may get wrapped to the next line, as shown here: This is the sentence, This is a new line Is there a way to fix this using CSS or jQuery? ...

To ensure proper display, the canvas should be set to display block when its width is 100vw and height is 100vh

Can anyone explain why I need to include display: block when my canvas is full page? Without it, the canvas size appears larger even though the width and height values are the same. Appreciate any insights. Thanks! ...

Bootstrap CDN causing modals to fail to appear

Here are the stylesheets I am currently using: script(src="/js/application.js") script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js") script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js") link(rel="styl ...

I'm curious if there's a method to ensure that the content within a mat-card stays responsive

So I'm working with this mat-card: <mat-card> <mat-card-content> <div *ngFor="let siteSource of siteSources | paginate: { itemsPerPage: 5, currentPage: page};"> <site-details [site]='siteSource'></s ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Encountering a surprise token error when using a material-ui example

I've been working on a reactjs web app using react-slingshot as the starting point. Everything was going smoothly until I decided to incorporate material-ui with `npm'. After adding an appbar and some buttons, the layout looked great. Then, I at ...

"Enjoying a table header that scrolls freely with autoscroll feature

Resolved - http://jsfiddle.net/CrSpu/11704/ I'm facing an issue with a table that has autoscroll functionality. I am looking to freeze the header of the table when automatic scrolling occurs, or you can test it out using my code pen. I'm uncer ...

Prevent Android WebView from attempting to fetch or capture resources such as CSS when using loadData() method

Context To many, this situation might appear to be repetitive. However, I assure you that it is not. My objective is to import html data into a WebView, while being able to intercept user hyperlink requests. During this process, I came across this helpfu ...

The last-of-type pseudo-class in Material-UI (MUI)

I'm attempting to apply a margin of 100px to the last <NotificationContainer> component. Unfortunately, the code snippet I have included is not achieving this desired effect. My project is being developed using MUI5. const Container = styled(&ap ...

Utilizing Material-UI CssBaseline with React JS

Looking to enhance the consistency of my new React app with a sleek design using Material-UI. Want it to be easy to maintain, so decided to start with the default theme. Trying out cssBaseline from Material-UI but running into issues. Not very familiar wit ...

Issue with AJAX show/hide causing scrolling to top

I've implemented ajax show hide functionality to display tabs, but whenever I scroll down to the tab and click on it, the page scrolls back to the top. You can check out the example code in this fiddle: http://jsfiddle.net/8dDat/1/ I've attempt ...

Ways to eliminate the up and down arrow in the MUI number field

How can I remove the up and down arrow from the MUI number field? My current version is 5.3.0. Is it possible to achieve this using the sx prop? Learn more about the sx prop here <TextField sx={{...}} id="outlined-number" label="Nu ...

Having trouble with the rendering of the Stripe Element Quickstart example

Currently, I am diving into the world of Stripe's Element Quickstart. Take a look at this fiddle that I have been working on. It seems to be quite different from the example provided. Although I have included the file, I can't seem to figure out ...

Comparison of single-line and multi-line CSS styles placement

There seems to be a debate among CSS developers regarding the preference for multi-line or single-line formatting. Some argue that multi-line is favored for its ease in finding specific properties within the CSS file. However, others believe that single- ...

Creative Vue.js and Tailwind CSS card layout featuring an image extending beyond the boundaries of the card

I'm attempting to design a card where an image pops out of the card. I've tried using z-index, but it doesn't seem to be working as expected. Here is the code I have: <div class="flex flex-col"> <div class=&quo ...

iPhone 5 Internet Browser - charcoal matte .png with transparent background

When it comes to web design, I often rely on 24-bit transparent .png files. Recently, I was reviewing a website on an iPhone 5 and noticed that all my .png files had a black matte around them. However, when I checked the same website on an iPhone 4, everyt ...

Failure to include jQuery and CSS in the AJAX response

Having trouble with my slider. The script that is added at runtime is not showing up in the ajax response. Does anyone know why this might be happening? $.ajax({ url:"ajax_get_response_eng_to_change.php", type:"POST", async:true, data:{c ...

Is there a mistake in the way I am creating a horizontal navigation bar?

Currently working on creating a simple navigation bar using HTML/CSS for a Java/Spring Boot project. Admittedly, my HTML/CSS skills are quite limited as you can see below. I'm aware that there might be some mistakes in my approach. Thank you in advanc ...

The ReactJS Material UI inputbase component is not correctly extracting the input value

Need help extracting user input text from Material UI InputBase component I know I'm missing something, but can't figure out what it is. import React from 'react' import { makeStyles } from '@material-ui/core/styles' import ...

Having difficulty removing padding from material-ui TabPane

Here is my TabPane: https://i.stack.imgur.com/Ihxmn.png I've been attempting to eliminate the padding. Some suggestions on SO led me to try this: <TabPanel value={value} index={i} classes={{ "& .MuiBox-root" ...