Last active
February 1, 2021 06:10
-
-
Save Manntrix/7c0eced0c89c391792eb65356545f338 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react' | |
import axios from 'axios' | |
import ReactPaginate from 'react-paginate'; | |
import './App.css' | |
export default class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
offset: 0, | |
data: [], | |
perPage: 10, | |
currentPage: 0 | |
}; | |
this.handlePageClick = this | |
.handlePageClick | |
.bind(this); | |
} | |
receivedData() { | |
axios | |
.get(`https://jsonplaceholder.typicode.com/photos`) | |
.then(res => { | |
const data = res.data; | |
const slice = data.slice(this.state.offset, this.state.offset + this.state.perPage) | |
const postData = slice.map(pd => <React.Fragment> | |
<p>{pd.title}</p> | |
<img src={pd.thumbnailUrl} alt=""/> | |
</React.Fragment>) | |
this.setState({ | |
pageCount: Math.ceil(data.length / this.state.perPage), | |
postData | |
}) | |
}); | |
} | |
handlePageClick = (e) => { | |
const selectedPage = e.selected; | |
const offset = selectedPage * this.state.perPage; | |
this.setState({ | |
currentPage: selectedPage, | |
offset: offset | |
}, () => { | |
this.receivedData() | |
}); | |
}; | |
componentDidMount() { | |
this.receivedData() | |
} | |
render() { | |
return ( | |
<div> | |
{this.state.postData} | |
<ReactPaginate | |
previousLabel={"prev"} | |
nextLabel={"next"} | |
breakLabel={"..."} | |
breakClassName={"break-me"} | |
pageCount={this.state.pageCount} | |
marginPagesDisplayed={2} | |
pageRangeDisplayed={5} | |
onPageChange={this.handlePageClick} | |
containerClassName={"pagination"} | |
subContainerClassName={"pages pagination"} | |
activeClassName={"active"}/> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much for this 🙏🏻 I finally managed to implement pagination after reading your article. I'm really grateful for your work!