Here is a simple example using library paginate-array to paginate array items stored in the component's state. If you inspect the source for paginate-array
, you'd see the logic for creating a "page" is fairly straightforward, so you may be able to use it for inspiration for your own pagination utilities. This example uses Todos from JSONPlaceholder, but you can modify the example as needed. Keep in mind the endpoint https://jsonplaceholder.typicode.com/todos
does not have objects with property name
as your example suggests. This example does simple checks for page numbers with the click handlers for the previous/next buttons to help ensure invalid pages cannot be selected. This example is assuming you plan to load all the data on the component loading, rather than requesting new pages of data via axios/fetch.
import React, { Component } from 'react';
import paginate from 'paginate-array';
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
size: 5,
page: 1,
currPage: null
}
this.previousPage = this.previousPage.bind(this);
this.nextPage = this.nextPage.bind(this);
}
componentDidMount() {
fetch(`https://jsonplaceholder.typicode.com/todos`)
.then(response => response.json())
.then(todos => {
const { page, size } = this.state;
const currPage = paginate(todos, page, size);
this.setState({
...this.state,
todos,
currPage
});
});
}
previousPage() {
const { currPage, page, size, todos } = this.state;
if (page > 1) {
const newPage = page - 1;
const newCurrPage = paginate(todos, newPage, size);
this.setState({
...this.state,
page: newPage,
currPage: newCurrPage
});
}
}
nextPage() {
const { currPage, page, size, todos } = this.state;
if (page < currPage.totalPages) {
const newPage = page + 1;
const newCurrPage = paginate(todos, newPage, size);
this.setState({ ...this.state, page: newPage, currPage: newCurrPage });
}
}
render() {
const { page, size, currPage } = this.state;
return (
<div>
<div>page: {page}</div>
<div>size: {size}</div>
{currPage &&
<ul>
{currPage.data.map(todo => <li key={todo.id}>{todo.title}</li>)}
</ul>
}
<button onClick={this.previousPage}>Previous Page</button>
<button onClick={this.nextPage}>Next Page</button>
</div>
)
}
}
export default TodoList;
Here is a basic example in action. The example also has an approach to handling a changeable size dropdown.
Hopefully that helps!