Simple React Js Pagination using React Hooks
2 min readAug 2, 2020
In this blog you will learn about creating a pagination with page numbers, next and previous buttons with minimalistic code, using react-js-pagination package.
Lets install `react-js-pagination` first.
npm i react-js-pagination
import React, { useState } from "react";
import Pagination from "react-js-pagination";
const PaginatedContent = () => { // Data to be rendered using pagination.
const todos = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; const todosPerPage = 3;
const [ activePage, setCurrentPage ] = useState( 1 );
// Logic for displaying current todos
const indexOfLastTodo = activePage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.slice( indexOfFirstTodo, indexOfLastTodo );
const renderTodos = currentTodos.map( ( todo, index ) => {
return <li key={ index }>{ todo }</li>;
} );
const handlePageChange = ( pageNumber ) => {
console.log( `active page is ${ pageNumber }` );
setCurrentPage( pageNumber )
};
return (
<div>
<div className="result">
{ renderTodos }
</div>
<div className="pagination">
<Pagination
activePage={ activePage }
itemsCountPerPage={ 3 }
totalItemsCount={ todos.length }
pageRangeDisplayed={ 3 }
onChange={ handlePageChange }
/>
</div>
</div>
)
}
export default PaginatedContent;
Now you can use the PaginatedContent in your project and edit the data and renderTodos function according to your needs. That’s all folks!
You can read more blocks on codeytek