Home > Software design >  using pagination leads back to the first page every time
using pagination leads back to the first page every time

Time:10-26

My application is a online book store (for now it runs on JS object data), and i want specific amount if books to be presented on every page. But the pagination i wrote causing problems.

though every click on each page leads to that page, displays the relevant cards, but then after one second it jumps back to show the content of the first page.

App:

 

import React,{useState, useMemo} from 'react'
import {Link} from 'react-router-dom'
import { useGlobalContext } from './context'
import Search from './Search'
import Pagination from './Pagination'
function Products() {

 

 const {books, addBookToCart} = useGlobalContext() 

const[currentBook, setcurrentBook] = useState(1)         
const [BooksPerPage]  = useState(3)   
const lastIndex = currentBook*BooksPerPage
const firstIndex = lastIndex-BooksPerPage
const currentPage = books.slice(firstIndex,lastIndex)

function paginate(pagenumber){setcurrentBook(pagenumber)}


 
   return (
    <>
                <Search></Search>
                 <div className='product-books'>
                 {currentPage.map((b)=> {
                     
                     return <div  className='product-books-inner'>
                         <Link to= {`${b.slug}`}>{b.name}<div className='cart-item'>                 
                        <img src={b.img}></img></div> </Link>
                     
                         <button className='clear-btn' onClick={()=>addBookToCart(b.slug)}>
                        add to cart</button>


                        <Link to= {`../container/${b.slug}`}><button>purchase</button></Link> </div> })}

                     
                     <Pagination paginate={paginate} BooksPerPage={BooksPerPage} 
                   total= {books.length}></Pagination>

                          </div>
    </>

   )
}

export default Products

Pagination:

import React from 'react'

function Pagination({BooksPerPage, total , paginate} ) {
    const pagenumbers = [ ]
    for (let i = 1; i <= Math.ceil(total /BooksPerPage) ; i  ) {
       pagenumbers.push(i)
        }

  return (
    <div>{pagenumbers.map((pn)=>(

          <span> <a href='' onClick={()=> paginate(pn)}>{pn}</a></span>

    ))}</div>
  )
}

export default Pagination

i found similar topics here on stack, like: Pagination: changed made on last page gone after switching back or Paging in react

but didn't success implement the advices from the, in my application. Appreciate any help.

CodePudding user response:

Now your page reloads every time, because you have <a href=''>

Replace <a> with <Link> and pass correct to parameter

or

Replace <a> with <button>

  • Related