Tips for dynamically incorporating points such as "..." to signify additional pagination buttons during web development

Can someone help me add a "..." between pagination buttons if there are more than five buttons in my code? Here is the current pagination script I have:

import React, { useState } from 'react'

const Pagination = ({productsPerPage, totalPosts, paginate}) => {
const [currentPage, setCurrentPage] = useState(0)
const PageNumbers =[]

const int = Math.ceil(totalPosts / productsPerPage)
    if (int === 1 ) return null 
    for (let i = 1; i<= int; i++) {
        PageNumbers.push(i) 
    }


    return (
        <nav className="">
            <ul className="pagination">
                 {PageNumbers.includes(currentPage - 1) && 
                <a className="page-link" href="!#" onClick={() => 
                    { setCurrentPage(currentPage - 1);  
                    paginate(currentPage - 1); }}> Previous
                 </a>}

                    {PageNumbers.map(number=> (
                        <li key={number} className={number === currentPage ? 'page-item' : 'page-item '}>
                            <a onClick={ ()=> paginate(number)} href="!#" className="page-link active">
                                {number} 
                            </a>
                        </li>
                    ))}

                 {PageNumbers.includes(currentPage + 1) && 
                <a className="page-link" href="!#" onClick={() => 
                    {setCurrentPage(currentPage + 1); 
                    paginate(currentPage + 1); }}> Next 
                </a>}
            </ul>
        </nav>
    )
}

export default Pagination

Answer №1

Update your returning function with the code snippet provided below:

return (
     <nav className="">
       <ul className="pagination">      
        {PageNumbers.map(number => (          
            (number < 3 || (number > currentPage-2 && number < currentPage+2) || 
               number > PageNumbers.length - 2 )  ?
           <li
              key={number}
              className={number === currentPage ? "page-item" : "page-item "}
           >
             <a
               onClick={() => paginate(number)}
               href="!#"
               className={"page-link " + number ===currentPage ?'active':''}
             >
                {number}
             </a>
          </li>
          :
          PageNumbers.length>5 && number < 4 ? '...'
          : 
          number < PageNumbers.length && number == currentPage+2 ? '...'
          :null

      ))}
    </ul>
   </nav>
);

The provided code snippet displays the first two page numbers, last two page numbers, current page number along with previous and next page numbers. All other page numbers will be represented by ellipses (...).

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

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

Turning JSON data into an array format, omitting the keys

Can someone help me with a query that will retrieve a specific column from the database and return it in this format: [ { "tenantName": "H&M" }, { "tenantName": "McDonalds" } ] I would like to transform ...

What is the best way to customize the color of the border and icon in an outlined MaterialUI input field

I'm a newcomer to materialUI and I have a question regarding customizing an outlined input field with an icon. Due to my dark background, I need the icon, border, and text color to be lighter, such as grey. Can someone please advise on the materialUI ...

The importance of accessibility features in Dropdown and Select menus

On a website dedicated to sports, I have three dropdown menus that allow users to make selections for different events and sports. Currently, the code is using buttons and anchor tags instead of the select/option or datalist elements. When selecting optio ...

(Reactjs) Steps to automate submission of file upon selection

I'm having trouble figuring out how to automatically submit an image using an input field without a submit button. My current approach involves selecting the file and then submitting it automatically. Here's what I have so far: const [image, setI ...

What could be the reason for ThemeProvider (Material UI) failing to function properly in this scenario?

I've encountered something puzzling with Material UI. Despite my experience with it, I can't seem to figure out why my H2 tag in the nested component is rendering in Times instead of Arial. I've double-checked the docs and my code, but the i ...

Why do I receive a URL like this when attempting to download a video from YouTube?

Can anyone explain to me why I am getting this URL error while trying to pull a video from YouTube? Error in console: GET http://localhost:3000/www.youtube.com/watch?v=IEDEtZ4UVtI 404 (Not Found) GET http://localhost:3000/www.youtube.com/watch?v=IEDEtZ4UVt ...

Tips for effectively structuring material-ui Grid in rows

I am currently using the material-ui framework to create a form. Utilizing the Grid system, I want to achieve the following layout: <Grid container> <Grid item xs={4} /> <Grid item xs={4} /> <Grid item xs={4} /> </Gr ...

Enhance autocomplete functionality by incorporating a left icon feature for text fields within the autocomplete component

I have a component with autocomplete functionality that displays tags Autocomplete with tags and I am trying to add a left icon, but only the right icon is functioning correctly. Current Issue When I add a left icon, it shows up but prevents the renderi ...

Limit the frequency of rendering JSX elements in React by implementing debouncing techniques

Is there a way to delay the rendering of a jsx element in order to smooth out the animation? I have an expanding panel with content inside, and when the panel is empty, the animation works well. However, if the panel already contains content, the expansion ...

Having trouble with react-unity-webgl integration in Next.js project

I've been trying to integrate this code into a Next.js build, but for some reason the game isn't loading on the page and I'm not seeing any errors in the console. I'm completely stumped as to why the game won't load. The tools I&a ...

What steps should I take to resolve the issue I am encountering while attempting to install packages using npm

npm ERR! Linux 4.15.0-36-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "create-react-app" npm ERR! node v8.10.0 npm ERR! npm v3.5.2 npm ERR! path /tmp/npm-7054-19e3727d npm ERR! code EROFS npm ERR! errno -30 npm ERR! syscall mkdir n ...

Encountered an error during the production build of NEXTJS, where it panicked due to the global thread pool not being initialized

While hosting my app on Heroku and running git push heroku main, I encountered the following error: panicked at 'the global thread pool has not been initialized.: threadpool builderror { kind: ioerror(error { kind: unsupported, message: "operatio ...

Implement user registration and authentication in your application using the powerful combination of React, Redux, and Express

I have a React and Redux application that utilizes Express and MongoDB. My goal is to allow users to register for an account, but I am struggling with how to make React/Redux send data to Express. In the long term, I want to store user account details such ...

Why am I getting undefined when passing useState as props in React?

I'm encountering a problem with my application. I'm working on creating a pizza store where users can add products to their cart easily. Using react router, I've set up the cart dropdown (it appears when you click on the cart icon) using use ...

Apply CSS styling (or class) to each element of a React array of objects within a Component

One issue I'm facing involves adding specific properties to every object in an array based on another value within that same object. One such property is the background color. To illustrate, consider an array of objects: let myObj = { name: "myO ...

ReactJS: Error - ReferenceError: React is not defined (no-undef)

I recently started learning React by following the tutorial on reactjs.org. After setting up my project using npm and creating my index.js file, I encountered an error: src\App.js Line 9:21: 'React' is not defined no-undef Line 42: ...

Design buttons that are generated dynamically to match the style

I have a challenge in styling dynamically generated buttons. I've developed a component responsible for generating these dynamic buttons. const TIMER_PRESETS: Record<string, number> = { FIFTHTEENSEC: 15, THIRTYSEC: 30, FORTYFIVESEC: 45, ...

Determining the installation duration of the React Native screen

Several questions have been asked about this topic, but none of them seem to have a definitive answer. What I am looking to do is calculate the time it takes to navigate to a screen. The timer will start here: navigation.navigate("SomePage") Essentially, ...

Pass the JSX data as JSON from the Express backend and showcase it as a component in the React frontend

I am currently developing a basic react front-end paired with an Express backend. Is it possible for me to have express send JSX data as JSON so that I can fetch it in react and utilize it as a component? Right now, I am sending JSON data and successfully ...