Simple example to create Pagination in React JS

Most of the interviewer ask you in the interview to create pagination to the list.

So here I will show you how to create simple and quick pagination component. I hope you know basics of reactjs to understand the code.

Each page I am displaying 6 list items.

I am using punkapi to fetch the records from the API.

https://api.punkapi.com/v2/beers?page=2&per_page=80

App.js

import React, { useState, useEffect } from ‘react’;

import ‘./style.css’;

import ListBeers from ‘./components/ListBeers’;

export default function App() {

const [beers, setBeers] = useState([]);

const [curr_page, setCurr] = useState(1);

const [prev_page, setPrev] = useState(0);

const [next_page, setNext] = useState(0);

useEffect(() => {

const page_step = 8;

const api = `https://api.punkapi.com/v2/beers?page=${curr_page}&per_page=${page_step}`;

fetch(api)

.then((res) => res.json())

.then((response) => {

setBeers(response);

})

.catch((error) => {

console.log(‘failed to load data’);

});

}, [curr_page]);

const updateBeer = () => {

console.log(curr_page);

const page_step = 8;

const api = `https://api.punkapi.com/v2/beers?page=${curr_page}&per_page=${page_step}`;

fetch(api)

.then((res) => res.json())

.then((response) => {

// console.log(response);

setBeers(response);

})

.catch((error) => {

console.log(‘failed to load data’);

});

};

const nextPage = () => {

updateBeer();

setCurr(curr_page + 1);

setPrev(curr_page);

};

const prevPage = () => {

if (curr_page > 1) {

updateBeer();

setCurr(curr_page — 1);

setPrev(curr_page);

} else {

alert(‘You are in the first page’);

}

};

return (

<div className=”main”>

<div className=”pagination”>

<button onClick={prevPage}>Prev</button>

<h3>Page: {curr_page}</h3>

<button onClick={nextPage}>Next</button>

</div>

<ListBeers beers={beers} />

</div>

);

}

ListBeers.js

import React, { useState, useEffect } from ‘react’;

export default function ListBeers({ beers }) {

return (

<div className=”card_container”>

{beers && beers.length > 0 ? (

<>

{beers &&

beers.map((item) => {

return (

<div key={item.id} className=”card” id={item.id}>

<h1>{item.name}</h1>

<img src={item.image_url} width=”100" height=”100" />

<div>{item.tagline}</div>

<div className=”disc”>

<i>{item.description}</i>

</div>

</div>

);

})}

</>

) : (

<h4>Loading…</h4>

)}

</div>

);

}

Final Output.

--

--

I am a software developer and international dance fitness instructor

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Manjunathkalburgi

Manjunathkalburgi

13 Followers

I am a software developer and international dance fitness instructor