I
I
Ihor S2021-01-08 18:01:13
React
Ihor S, 2021-01-08 18:01:13

How to make dots in React pagination?

I made the logic, everything works. But the dots don't work. Need to show dots before the last page. And show the last page number. And shift the first numbers as you switch. That is, in the beginning there should be 10 numbers, then ... and the last page
z6xX8.png
The Pagination component.

import React, { useState, useEffect } from 'react'
import './Pagination.scss'

export default function Pagination({ totalPages, onPageChange }) {
  const [pages, setPages] = useState([])
  const [selectedPage, setSelectedPage] = useState(1)

  useEffect(() => {
    getNumbersPages(totalPages)
  }, [totalPages])

  const getNumbersPages = totalPages => {
    let pagesNumber = [];
    for (let i = 0; i < totalPages; i++) {
      pagesNumber.push(i + 1);
    }
    setPages(pagesNumber)
  };

  const handlePageChangeLeft = (e) => {
    onPageChange(e)
    if (selectedPage <= 1) {
      return
    } else {
      setSelectedPage(selectedPage - 1)
    }
  }

  const handlePageChangeRight = (e) => {
    onPageChange(e)
    if (selectedPage >= pages.length) {
      return
    } else {
      setSelectedPage(selectedPage + 1)
    }
  }

  const handlePageChange = (e, page) => {
    onPageChange(e)
    setSelectedPage(Number(page))
  }

  return (
    <div className='pagination'>
      <button className="pagination__btn pagination__btn--left" data-page={selectedPage} onClick={(e) => handlePageChangeLeft(e)}>{selectedPage === 1 ? selectedPage : selectedPage - 1}</button>
      <div className="pagination__numbers">
        {pages.map((page, i) => (
          <div>
            { /// вот здесь не могу додуматся алгоритм
              i < selectedPage+11 &&
              <div key={page} data-page={selectedPage} className={selectedPage === page ? 'pagination__page pagination__page--active' : 'pagination__page'} onClick={(e) => handlePageChange(e, page)}>
                {page === selectedPage+10 ? '...' : page}
              </div>
            }
          </div>
        ))}
      </div>
      <button className="pagination__btn pagination__btn--right" data-page={selectedPage} onClick={(e) => handlePageChangeRight(e)}>{selectedPage === totalPages ? selectedPage : selectedPage + 1}</button>
    </div>
  )
}
totalPages - Number

My bug
kcaVs.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2021-01-08
@SilenceOfWinter

https://developer.mozilla.org/en/docs/Web/JavaScri...
+
https://developer.mozilla.org/en/docs/Web/JavaScri...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question