1

I am new to React and material UI. I want when the user changes rowperpage from drop-down than I want to scroll at the top of my window. I have used Table in which for pagination I have written code like-

            rowsPerPageOptions={[5, 10, 25]}
            component="div"
            count={users.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onChangePage={handleChangePage}
            onChangeRowsPerPage={handleChangeRowsPerPage}

          />

functions called are written like this

const handleChangePage = (event, newPage) => {
    window.scrollTo(0, 0);
    setPage(newPage);

  };


  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
window.scrollTo(0,0);   
  };

I tried using window.scrollTo(0,0), for handleChangePage its working but for handleChangePerPage its not working.

1
  • <TablePagination rowsPerPageOptions={[5, 10, 25]} component="div" count={users.length} rowsPerPage={rowsPerPage} page={page} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} /> Commented Apr 28, 2020 at 10:05

1 Answer 1

3

After digging for three hours I found that you have to add the following prop to thetablePagination component as well as adding the ref as per other great answers explained (How to scroll to an element?):

SelectProps(https://github.com/mui-org/material-ui/blob/f013f19bc2792a25663e8a3658aed0365c0a1964/packages/material-ui/src/TablePagination/TablePagination.js#L118) and I use scrollIntoView instead of scrollTo option.

So change your code to the following it should work:

  const tableRef = React.useRef(null)
...

<TableContainer component={Paper} ref={tableRef}>
...

<TablePagination
  rowsPerPageOptions={[5, 10, 25]}
            component="div"
            count={users.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onChangePage={handleChangePage}
            onChangeRowsPerPage={handleChangeRowsPerPage}
            SelectProps={{
          inputProps: { "aria-label": "rows per page" },
          native: true
        }}

          />
const handleChangeRowsPerPage = (event) => {
    tableRef.current && tableRef.current.scrollIntoView();

    setRowsPerPage(parseInt(event.target.value, 10))
    setPage(0)
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.