DEV Community

Ridha Mezrigui
Ridha Mezrigui

Posted on • Updated on

React : Make your own pagination

hello community,

today i'll show you how to make your own pagination without using any package.

let's get started

Alt Text

first thing we need to do is to create a react app

npx create-react-app make-pagination
cd make-pagination //navigate to our project
code . //open our react app with vscode
Enter fullscreen mode Exit fullscreen mode

let's say that we want to fetch the data of our users and for that
i'll use Mockaroo to generate a dummy data.
in src folder we create a new file data.js this file will contain the users dummy data.

//data.js
export const Data = [
{"id":1,"name":"Anna-maria","email":"ajehaes0@vinaora.com"},
{"id":2,"name":"Kenyon","email":"kvarfalameev1@wikimedia.org"},
{"id":3,"name":"Twila","email":"tkelby2@amazon.com"},
{"id":4,"name":"Rudd","email":"rcatling3@about.me"},
{"id":5,"name":"Robby","email":"rbenini4@behance.net"},
{"id":6,"name":"Viviyan","email":"vcurlis5@addtoany.com"},
{"id":7,"name":"Gabriello","email":"gdaines6@purevolume.com"},
{"id":8,"name":"Carter","email":"ckoubek7@wikipedia.org"},
{"id":9,"name":"Berna","email":"bdimatteo8@umich.edu"},
{"id":10,"name":"Marlow","email":"mhedditch9@usda.gov"},
{"id":11,"name":"Corella","email":"cdiperausa@newsvine.com"},
{"id":12,"name":"Cherida","email":"cstarkieb@vk.com"},
{"id":13,"name":"Zackariah","email":"zbathoc@cam.ac.uk"},
{"id":14,"name":"Orelee","email":"ogabitsd@msu.edu"},
{"id":15,"name":"Alonzo","email":"aclaire@fc2.com"},
{"id":16,"name":"Vonnie","email":"vkillbyf@cornell.edu"},
{"id":17,"name":"Weidar","email":"wdeyesg@whitehouse.gov"},
{"id":18,"name":"Cyb","email":"cternouthh@surveymonkey.com"},
{"id":19,"name":"Melisent","email":"modayi@loc.gov"},
{"id":20,"name":"Darbee","email":"djanecekj@stumbleupon.com"}
]
Enter fullscreen mode Exit fullscreen mode

now let's fetch these users without pagination
first we create a "user" folder then we create two files user.jsx component and user.css cuz we need some basic css style.

//user.jsx
import React from 'react';
import './user.css';

const User = ({name, email}) => {
    return ( 
        <div className='user'>
            Name : {name} <br/>
            Email : {email}
        </div>
     );
}

export default User;
Enter fullscreen mode Exit fullscreen mode
/* user.css */
.user{
    padding: 10px;
    margin:10px auto;
    width:50%;
    border : 1px solid #eee;
}
Enter fullscreen mode Exit fullscreen mode

in the "App.js" component we import user.jsx and Data.js and fetch our data.

//App.js
import React from 'react';
import './App.css';
import { Data } from './data';
import User from './user/user';

function App() {
  return (
    <div className="App">
    <h1>ALL USERS</h1>
      {
        Data.map(user => <User key={user.id}
                               name={user.name}
                               email={user.email} />
        )
      }
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

the result
Alt Text

20 users in the same page is a little bit annoying in this case we need to use pagination.

Create the pagination component

1- create pagination folder contain two files pagination.jsx and pagination.css.

first we need to install a lodash package

npm i --save lodash
Enter fullscreen mode Exit fullscreen mode
//pagination.jsx
import React from 'react';
import _ from 'lodash';
import './pagination.css';

const Pagination = (props) => {

    const { itemsCount, pageSize, currentPage, onPageChange } = props;
    const pageCount = Math.ceil(itemsCount / pageSize);
    if (pageCount === 1) return null;
    const pages = _.range(1, pageCount + 1);

    return (
        <div className="pagination">
            {pages.map(page => (
                <div href={null} key={page}
                    onClick={() => onPageChange(page)}
                    className={page === currentPage ? 'active' : 'page-item'}>
                    {page}
                </div>
            ))}
        </div>
    )
}

export default Pagination;
Enter fullscreen mode Exit fullscreen mode

itemsCount, pageSize, currentPage and onPageChange are props we will pass them when we implement the pagination in the App.js component.

/* pagination.css */
.pagination {
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination div {
  color: white;
  float: left;
  padding: 8px 16px;
  display: block;
  text-decoration: none;
  transition: background-color 0.3s;
  cursor: pointer;

}

/* Style the active/current link */
.pagination div.active {
  background-color: #05aff1;
}

/* Add a grey background color on mouse-over */
.pagination div:not(.active) {
  background-color: #444444;
}


Enter fullscreen mode Exit fullscreen mode

2- Create a javascript logic that will slice our dummy data

in the src folder we create a paginate.js file

import _ from 'lodash';

export function paginate(items, pageNumber, pageSize){
   const startIndex = (pageNumber - 1) * pageSize;

   return _(items)
            .slice(startIndex)
            .take(pageSize)
            .value();
}
Enter fullscreen mode Exit fullscreen mode

this function take all data (items), pageNumber (the number of page we want to go if we have 20 users and and we want 4 users in each page 20/4=5pages if we want to see the users in page 3 we start slice our data from index: (3-1)*4=8), the pageSize (number of users in each page) and return new table contain a pageSize elements.

3- Implement the pagination

in App.js component :
import paginate function from paginate.js and import useState hook then

  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 4;

  const handlePageChange = page => {
    setCurrentPage(page);
  }

  const getPageData = () => {

    const paginationData = paginate(Data, currentPage, pageSize);
    return { totalCount: Data.length, data: paginationData }
  }

  const { totalCount, data } = getPageData();
Enter fullscreen mode Exit fullscreen mode

now let's import pagination component and see the result

const { totalCount, data } = getPageData();
  return (
    <div className="App">
      <h1>ALL USERS</h1>
      {
        data.map(user => <User key={user.id}
          name={user.name}
          email={user.email} />
        )
      }
      <Pagination
        itemsCount={totalCount}
        pageSize={pageSize}
        currentPage={currentPage}
        onPageChange={handlePageChange} />
        page {currentPage} of { totalCount / pageSize }
    </div>
Enter fullscreen mode Exit fullscreen mode

the final result
Alt Text

Alt Text

I hope you enjoyed this blog.

Top comments (0)