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:

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

Bizarre Drop-down Peculiarities

Having a perplexing issue where the 'search' list item is oddly shifted below the dropdown box only when it is displayed. The other list items remain in their correct positions. Any advice on how to resolve this? The appearance and functionality ...

Tips for choosing a particular list item using jQuery: retrieve the attribute value of 'value' and showcase it on the webpage

I have a task that requires the following: Implement an event listener so that when you click on any list item, the value of its "value" attribute will be shown next to this line. In my HTML, I have an ordered list with 8 list items. The values range fro ...

The page refreshes when the anchor element is clicked

Currently, I am working on enhancing a web application that is built on the foundation of traditional aspx (asp.net) web forms with elements of Angular 6 incorporated into it. My current assignment involves resolving a bug that triggers a page refresh whe ...

Creating aliases for a getter/setter function within a JavaScript class

Is there a way to assign multiple names to the same getter/setter function within a JS class without duplicating the code? Currently, I can achieve this by defining separate functions like: class Example { static #privateVar = 0; static get name() ...

What is the best way to set up an anchor element to execute a JavaScript function when clicked on the left, but open a new page when clicked in

One feature I've come across on certain websites, like the Jira site, is quite interesting. For instance, if we take a look at the timeline page with the following URL - When you click on the name of an issue (which is an anchor element), it triggers ...

Every time I attempt to install a dependency, I encounter the same frustrating error

npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3556464d5c67584b59695048564d494048470961020505"> ...

``Is there a more SEO-friendly option instead of using an iframe?

I am looking for a solution to easily share my content with other websites without the issues I currently face. Presently, I use an iframe which poses two problems: <iframe width=“540”; height=“700” frameborder=“0” src=“http://www.energi ...

"Optimizing Performance: Discovering Effective Data Caching

As a developer, I have created two functions - one called Get to fetch data by id from the database and cache it, and another called POST to update data in the database. However, I am facing an issue where I need to cache after both the get and update oper ...

Ensure that only one Accordion in React MUI is always open

import React, { useState } from "react"; import { Accordion, AccordionDetails, AccordionSummary, Typography } from "@mui/material"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; export default function ...

Having trouble with NextAuth's Google provider on Safari?

I've encountered an issue where the Google provider works perfectly on Chrome and other browsers, but fails to work on Safari. Despite going through the documentation thoroughly, I couldn't find any relevant information to resolve this. This is ...

The JQxTreeGrid is displaying properly, however, it is not loading the data from the JSON source

Looking for some assistance with loading Json data into a Jquery grid using jqxTreegrid. Currently, the grid is displaying but not the data. Despite no errors in the debugger, I'm unable to figure out the issue. Any help resolving this matter would be ...

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

What is the method for adjusting the Accept-Language header in axios using next-i18next outside of a component?

I have been working on exporting a custom function called setLanguageHeader in order to modify the Accept-Language header used by axios. In my axios file, I encapsulated the code as follows: requests.ts: import axios, { AxiosRequestConfig } from 'ax ...

The message "Error: Unknown custom element: <router-view> - have you properly registered the component?" is prompting for a solution

Even though the name is correctly capitalized in all my component instances, I am still encountering an error. After researching similar issues online, it appears that the problem usually revolves around naming discrepancies. However, I have double-checked ...

React JS routes function properly only upon being reloaded

Encountering a problem with my reactJS routes where the URL changes in the address bar when clicking on a link, but the component does not render unless I refresh the page. Here is an excerpt from my code: index.js import React, { Component } from &apos ...

Requesting an API token through the body using Javascript's Fetch function

I'm currently working on developing a frontend application using Javascript Fetch to interact with an API service. One of the tasks I need to accomplish is to create a token by using the POST method and sending an apiKey parameter in the Body. Once I ...

I am facing an issue with effectively passing properties from a parent state to its child component

In the Login component, I set the authentication state using the token as false initially. After a successful login, the token is changed to true. function Login() { const [user, setUser] = useState({ name: '', email: '' }); const [ ...

What is the best way to verify the input of a TextField element?

When I visited the Material UI Components documentation for TextField, I was hoping to find an example of validation in action. Unfortunately, all they showed was the appearance of the invalid TextField without any insight into the actual validation code i ...

Is there a way to enhance the react-leaflet Map component by incorporating the leaflet.contextmenu feature?

The react-leaflet-context-menu plugin serves as the react version of leaflet.contextmenu. It differs in that it utilizes the original leaflet map to implement the plugin in react rather than using react-leaflet. Incorporating react-leaflet into my applica ...

Maintaining the original layout upon refreshing the page

Incorporating two forms on my website, I added a button that transitions between the login and sign-up forms smoothly. The process is as follows: Initially, the login form is displayed; clicking the button switches to the sign-up form. Proceeding to subm ...