Leverage Turing Intelligence capabilities to integrate AI into your operations, enhance automation, and optimize cloud migration for scalable impact.
Advance foundation model research and improve LLM reasoning, coding, and multimodal capabilities with Turing AGI Advancement.
Access a global network of elite AI professionals through Turing Jobs—vetted experts ready to accelerate your AI initiatives.
Understanding how to use pagination in React can help you create websites that are user-friendly by helping users navigate through large amounts of data. It also improves load time, thereby making websites faster. Certain projects require large sets of data and need pagination, such as HR dashboards, bank statements, and store inventories.
Pagination in websites is subject to a developer’s preference and there are no stringent rules on how to create it. However, a popular convention is to present data in bits of 10 or at most, 15 sets of data at once.
We start by installing a React application using Next and also install a package called react-paginate. This is a custom component that handles pagination of data with simple implementations.
To install Next, we use the command npx create-next-app@latest. For react-paginate, we use npm install react-paginate. React paginate is an easy-to-use library that provides a component with some properties to create pagination and configure it properly.
We will create a table of 10 rows per page by consuming an API using useSWR, which is a package provided by the Next framework and is useful for connecting to APIs. The package is exceptional as it helps to track error, loading and data states.
To get the data for the pagination with useSWR, we pass in our API and our method.
const fetcher = (...args) => fetch(args).then(res => res.json()) const { data, error, isLoading } = useSWR('https://6270020422c706a0ae70b72c.mockapi.io/lendsqr/api/v1/users', fetcher)
Using destructuring, we are able to track the data, error, and loading state. This data provides an array of 100 specific items which we will convert to a table of 10 rows using the installed react-paginate.
To use this library, we will import react-paginate and write some methods that will be passed to the props.
React-paginate accepts some props, including:
import useSWR from 'swr' import ReactPaginate from 'react-paginate'export default function Dashboard() { const fetcher = (...args: any) => fetch(args).then(res => res.json()) const { data, error, isLoading } = useSWR('https://6270020422c706a0ae70b72c.mockapi.io/lendsqr/api/v1/users', fetcher)
const [itemOffset, setItemOffset] = useState(0) const itemsPerPage = 10; const endOffset = itemOffset + itemsPerPage; const currentItems = data.slice(itemOffset, endOffset); const pageCount = Math.ceil(data.length / itemsPerPage); const handlePage = (evt) => { const newOffset = (evt.selected * itemsPerPage) % data.length; setItemOffset(newOffset) }</pre><p>To implement pagination, we will track the number of items displayed with the itemOffset, starting with 0, which is continually incremented with the number of items already displayed.</p><p>The itemsPerPage is the number of items we want displayed at once. It can be set to any number. We set it to 10 in this React pagination example.</p><p>The endOffset is a summation of itemOffset and itemsPerPage.</p><p>The currentItems is the actual array that we display at one time which is possible by using the slice method of an array. It accepts two parameters, including the itemOffset, which is where we want to start the array from, and the endOffset, which is where we want the array to stop at a certain time.</p><p>To get the 'pageCount', we divide the data.length by the number of itemsPerPage that we pass to math.ceil to get an integer value.</p><p>The 'handlePage' method is called to the 'onPageChange' change event which sets a new offset to the 'itemOffset' by multiplying the selected digit with the 'itemsPerPage'. This is divided by the total number of items in our array with 'data.length'.</p><pre>return ( <section> <div className={styles.wrapper}> <table className={styles.table}> <thead className={styles.thead}> <tr className={styles.thead}> <th className={styles.td}><span>ORGANIZATION</span><span></span></th> <th className={styles.td}><span>USERNAME</span><span></span></th> <th className={styles.td}><span>EMAIL</span><span></span></th> <th className={styles.td}><span>PHONE NUMBER</span><span></span></th> <th className={styles.td}><span>DATE JOINED</span><span></span></th> </tr> </thead> <tbody className={styles.tbody}> {currentItems.map((val: any, i: any) => { return <tr className={styles.tr} key={i}> <td className={styles.td}>{val.orgName}</td> <td className={styles.td}>{val.userName}</td> <td className={styles.td}>{val.email}</td> <td className={styles.td}>{val.phoneNumber}</td> <td className={styles.td}>{val.createdAt}</td> </tr> })} </tbody> </table> <ReactPaginate activeClassName={styles.activeLink} containerClassName={styles.pager} pageCount={pageCount} onPageChange={handlePage} pageRangeDisplayed={5} previousLabel='Prev ' breakLabel='...' pageClassName={styles.page} previousClassName={styles.prev} nextClassName={styles.prev} nextLabel='Next' disabledLinkClassName={styles.linkdisabled} disabledClassName={styles.disabled} /> </div> </section> )</pre><p>To get each table, we map through the currentItems we got from slicing through the actual array which is updated through the pagination buttons.</p><p>React-paginate provides a component to which we pass in all our props discussed earlier. By default, 'react-paginate' does not style the pagination. We can do it by assigning specific classnames.</p><ul><li>activeClassName: A prop for the page we are currently on.</li><li>containerClassName: A prop for the container component, which is reactPaginate.</li><li>pageClassName: A prop for each list item in the component.</li><li>previousClassName: A class name for the previous buttons.</li><li>nextClassName: A class name for the next buttons.</li><li>disabledLinkClassName: A class name for the anchor tag in the lists.</li><li>disabledClassName: A class name for the list tags.</li></ul><p>To style the table, we add borders, border radius, and background color. The table head text is bold by default, which is styled by using semantic tags:</p><pre>.table {
border: 1px solid gray; text-align: center; border-radius: 5px; margin-top: 40px; }
.td{ padding: 10px; }
To space each element in each cell, we add a padding of 10px that adds 10px on every side.
To add a background color to every even cell, we use a CSS pseudo element that allows us to target every even cell which then adds the specified background color.
.tr:nth-child(even){ background-color: rgba(167, 163, 163, 0.366); }
This is a CSS function for targeting different parts of elements by using simple mathematics. The 'nth-child()' accepts different parameters including odd and even numbers.
To style the pagination, 'react-paginate' library already provides us with classnames that can be used to style paginations to our satisfaction.
Using the props provided, we pass a classname that helps to style the pagination when interacted with:
.activeLink { border: none; color: white; cursor: pointer; background-color: rgba(136, 164, 226, 0.797); outline: none; }.containerClassName{ display: flex; justify-content: space-between; align-items: center; width: 50vw; font-weight: bold; } .pageClassName { border: 1px solid gray; border-radius: 50%; padding: 10px; } .previousClassName { font-weight: bold; padding: 6px; color: white; border-radius: 5px; background-color: rgba(136, 164, 226, 0.797); }
.disabledClassName { opacity: 0.6; }
React pagination is an essential part of creating a good user experience by not dumping too much information. It improves load time, which can reduce bounce rate, and facilitates a tidy user interaction.
Implementing react-paginate is extremely easy, thanks to its simple syntax. The pagination is created by using the slice method on the array of information and passing a method to the pageChange event which is responsible for updating the pagination. Pagination is further made easier by allowing the use of style props to allow it to carry the desired shape.
David is a technical writer and front end developer. He has successfully published several articles on web technologies and worked with teams in creating scalable softwares. He has contributed to open source projects and also specializes in frameworks like angular, react, node among other technologies.