Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved.

import React from "react";
import {
  gridPageCountSelector,
  gridPageSelector,
  gridPageSizeSelector,
  useGridApiContext,
  useGridSelector,
} from "@mui/x-data-grid";
import Pagination from "@mui/material/Pagination";
import PaginationItem from "@mui/material/PaginationItem";
import { Stack, TextField } from "@mui/material";
import { makeStyles } from "@mui/styles";

const useStyles = makeStyles(() => ({
  pagination: {
    "& .MuiPaginationItem-root": {
      padding: "14px",
      margin: "0", // Your custom pagination item styles here
      color: "#222124",
      fontSize: "14px",
    },
  },
}));

export default function CustomPagination() {
  const apiRef = useGridApiContext();
  const page = useGridSelector(apiRef, gridPageSelector);
  const pageCount = useGridSelector(apiRef, gridPageCountSelector);
  const pageSize = gridPageSizeSelector(apiRef, gridPageSizeSelector)
  const classes = useStyles();

  return (
    <Stack direction="row" justifyContent="space-between" width="100%" alignItems="center" sx={{ background: "#FAFAFA", padding: "16px" }}>
      <Stack direction="row" alignItems="center" style={{ fontSize: "14px" }}>
        <div>
          Currently Displaying:
        </div>
        <div>
          <TextField
            variant="outlined"
            type="number"
            value={pageSize}
            onChange={(e) => {
              if (!isNaN(e.target.value) && e.target.value >= 1 && e.target.value <= apiRef.current.getRowsCount()) {
                apiRef.current.setPageSize(e.target.value);
              }

            }}
            sx={{
              display: 'flex', 
              width: '68px',   
              alignItems: 'center', 
              gap: '8px',
              background: "white",
              margin: "0 5px"
            }}
          />
        </div>
        <div>
          Total Results: <span style={{ fontWeight: "700" }}>{apiRef.current.getRowsCount()}</span> {/* Corrected method name to getRows() */}
        </div>
      </Stack>

      <Pagination
        className={classes.pagination}
        color="primary"
        variant="outlined"
        shape="rounded"
        size="small"
        page={page + 1}
        count={pageCount}
        renderItem={(props2) => <PaginationItem {...props2} disableRipple />}
        onChange={(event, value) => apiRef.current.setPage(value - 1)}
      />
    </Stack>
  );
}

Answer №1

According to the MUI Pagination Custom Icons guide, you have the ability to customize icons for the next and previous buttons by utilizing the next and previous slots with the help of the slots property found in the PaginationItem component.

For instance:

import * as React from "react";
import Pagination from "@mui/material/Pagination";
import PaginationItem from "@mui/material/PaginationItem";
import Stack from "@mui/material/Stack";
import MyBackIcon from "@mui/icons-material/SubdirectoryArrowLeft";
import MyNextIcon from "@mui/icons-material/TurnRight";

export default function CustomIcons() {
  return (
    <Stack spacing={2}>
      <Pagination
        count={10}
        renderItem={(item) => (
          <PaginationItem
            slots={{ previous: MyBackIcon, next: MyNextIcon }}
            {...item}
          />
        )}
      />
    </Stack>
  );
}

This customization can result in:

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

Check out the working demo on Code Sandbox: https://codesandbox.io/s/mui-pagination-custom-icons-xf28cs

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 simultaneously run both my Node application and React app with just one command?

I am planning to create a boilerplate for React and Node, with the following root folder structure: - (root level) - client - src - public - package.json - ... - package.json - server.js - node_module ...

Error: Cannot access 'muiName' property as it is undefined

i am trying to display the elements of an array within a custom card component in a grid layout. However, when the page loads it freezes and the console shows "Uncaught TypeError: Cannot read property 'muiName' of undefined" custom car ...

Preserve the timestamp of when the radio query was chosen

I'm interested in finding a way to save the user's selected answer for a radio button question and track the time they saved it. Is there a way to achieve this using HTML alone? Or would I need to utilize another coding language or package? Just ...

Developing a personalized loop in handlebars templates

Just starting out with NodeJS and ExpressJS. I'm looking to customize a for loop in order to iterate through data from NodeJS using an index, akin to a non-traditional for loop. Take a look at the code snippet below, extracted from NodeJS, where I re ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

Troubleshooting: The issue of Vue JS not successfully navigating between web

After countless attempts, I am still struggling to get my Firebase login function to appropriately switch the component upon signing in. I urgently need assistance with configuring my router to seamlessly transition to the next page once the sign-in proces ...

Creating a class that can be easily mocked for connecting to mongoDB

I've been attempting to develop a class that connects to MongoDB (and accesses a gridFS connection using gridfs-stream). However, I have encountered two specific problems: Sometimes, I receive the mongo Error server instance in invalid state connect ...

Tips for accessing the value from an input field in an AngularJS application

Looking at my DOM structure below, <input class="k-textbox ng-pristine ng-untouched ng-valid ng-valid-required" type="text" placeholder="" ng-blur="controller.isDirty=true" ng-change="controller.isDirty=true" ng-model="controller.model.value" ng-requir ...

Why does the "margin" CSS style fail to function properly in FlowPanel within GWT?

I'm currently working with Gwt and have encountered a problem with styling buttons. Let's take a look at the following code snippet: .marginRight{ margin-right: 10px; } FlowPanel myFP=new FlowPanel(); Button myButton=new Button("Button"); Butt ...

Running time assessment for JavaScript executions

My current focus is on the execution time of JavaScript programs. Upon running them with nodejs/v8, I have noticed that the time command in the shell produces inconsistent results for execution times. Is there a method to sandbox the execution of these pr ...

When I add text to div boxes, they begin to drift downward

After creating four div boxes with content, I encountered an issue. Initially, when inserting filler text, everything seemed fine. However, as soon as I started adding actual content into the first box, the other three boxes shifted downwards by the same a ...

The interaction between jQuery Masonry and Bootstrap results in unexpected grid behavior

I've spent hours trying to solve this problem, but I can't seem to get it to work as intended. I want the layout of my boxes to be like this using Bootstrap grids: However, after implementing the jQuery Masonry plugin (which I used to manage va ...

Initiate the IE driver in WebDriver NodeJS with the option to disregard protected mode settings and possibly introduce flakiness

I'm attempting to create a driver session using IE capabilities to bypass protected mode settings in Internet Explorer, but I'm unsure of the correct syntax. I've experimented with the following: var driver = new webdriver.Builder().wi ...

Implement Babel with node.js 6.9

It puzzles me why some folks opt to use Babel for their Node.js projects. I personally utilize node 6.9 and have no issues writing ES6 code - from default arguments in functions to arrow functions, rest parameters, and spread syntax. Do you think Babel is ...

Execute JavaScript after authentication instead of forwarding the user to another page

Short version: How can we efficiently handle a second AJAX call after an ASP.NET Membership Authentication response? Long version: Let's say we have a web-based Paint program created using ASP.NET MVC. A user is painting a picture when suddenly their ...

Next/React - Iterate (increase by one row every 125 data points)

The purpose of the following code is to dynamically adjust the size of a textarea based on the length of extracted data. { logData.description.length < 125 ? ( <> <FormControl id='descriptionFormID' ref={te ...

React Bootstrap encountered rendering issues

Recently, I decided to delve into the world of React Bootstrap and started my learning journey. To get started, I followed some tutorials on <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="vi ...

Tips for effectively handling notifications using a single state management system

This React project showcases the Notification System demo provided by Mantine. It includes several function components utilizing notification. const A = () => { useEffect(() => { notifications.show({ // config }); }, []); retur ...

Retrieving an Ajax response by using form.submit() and sending it to PHP

After spending hours trying to mix a form.submit() call with a jquery/ajax call in order to receive a response from my php login script, I am at a loss. Despite looking through countless posts and examples on the same topic, I can't seem to find a sol ...

I have a `null` input value. Is there a way to compute this value in relation to a date

When the input is null, what can be done to calculate the value with date? https://i.stack.imgur.com/DmFsJ.png /* // ======================================================== * * * * * How To Calculate Input Value With Date When Input Is Null * * */ // ...