Skip to content

Instantly share code, notes, and snippets.

@E-fais
Created August 27, 2022 18:28
Show Gist options
  • Save E-fais/f2d82b1f65fb611819607f4737ea8d4f to your computer and use it in GitHub Desktop.
Save E-fais/f2d82b1f65fb611819607f4737ea8d4f to your computer and use it in GitHub Desktop.
//example without pagnation:-
const [myState,setMystate]=useState([])
//set some values for the state
myState.map(item=>{
<h1>{item.title}</h1>
})
//example for mui pagination:-
const [myState,setMystate]=useState([])
//set some values for the state
//install mui and import pagination in your file
import {Pagination} from "@mui/material"
//create a new state.
const [currentPage,setCurrentPage]=useState(1)
//create some variables for pagination
const itemsPerPage=9
const indexOffLastItem=currentPage*itemsPerPage
const indexOfFirstItem=indexOffLastItem-itemsPerPage
constPaginatedItems=myState.slice(indexOfFirstItem.indexOffLastItem)
// functiom to make the next and prev button work
const paginate=(e,value)=>{
setCurrentPage(value)
window.scrollTo({top:100,behavior:'smooth'}) //scroll page to top eon clicking next and prev button
}
//map items
{paginatedItems.map((item)=>{
<h1>{item.title}</h1>
})
}
//create page numbers & apply styling
<div>
{myList.length>0 &&
(
<Pagination
count='small'
variant='outlined'
count={Math.ceil(myList.length/itemsPerPage)} //math.ceil is used to make the decimal value round to next integer
defaultPage={1}
page={currentPage}
onChange={paginate}
/>
)}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment