I succeded to paginate my posts but couldn't add next and prev buttons and make them dynamically using this code snippet:
import React from 'react'
const Pagination = ({postsPerPage, totalPosts, paginate}) => {
console.log(totalPosts)
const PageNumbers = []
const int = Math.ceil(totalPosts / postsPerPage)
if (int === 1 ) return null
for (let i = 1; i<= int; i++) {
PageNumbers.push(i)
}
return (
<nav aria-label="Page navigation example">
<ul className="pagination">
{PageNumbers.map(number=> (
<li key={number} className="page-item">
<a onClick={ ()=> paginate(number)} href="!#" className="page-link">
{number}
</a>
</li>
))}
</ul>
</nav>
)
}
export default Pagination
please help to find way to include these buttons next and prev dynamically to my pagination who appears down. It's working great but needs next and prev
Let's give your component some state so it can know the current page and, therefore, can know how to go to the next page. This should get you pretty close!
import React, { useState } from 'react'
const Pagination = ({postsPerPage, totalPosts, paginate}) => {
const [currentPage, setCurrentPage] = useState(0)
console.log(totalPosts)
const PageNumbers = []
const int = Math.ceil(totalPosts / postsPerPage)
if (int === 1 ) return null
for (let i = 1; i<= int; i++) {
PageNumbers.push(i)
}
return (
<nav aria-label="Page navigation example">
<ul className="pagination">
{PageNumbers.includes(currentPage - 1) && <a onClick={() => {
setCurrentPage(currentPage - 1);
paginate(currentPage - 1);
}}>}
Prev
</a>
{PageNumbers.map(number=> (
<li key={number} className="page-item">
<a onClick={()=> {
setCurrentPage(number)
paginate(number)
}} href="!#" className="page-link">
{number}
</a>
</li>
))}
{PageNumbers.includes(currentPage + 1) && <a onClick={() => {
setCurrentPage(currentPage + 1);
paginate(currentPage + 1);
}}>}
</ul>
</nav>
)
}
export default Pagination
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With