Pagination with the Rick and Morty API
Tags: javascript, react, beginners, tutorial
Published: 2023-05-03 06:31:48

Most websites today can’t show all the data users need to see at once. It is better not to show all data because it makes for a better user experience and it also makes websites easier to navigate.

In order to show more data, a feature known as pagination can be implemented. I decided to give pagination a try and implement it using the Rick and Morty API. I chose this API because it made it easier to implement pagination in my opinion. I will show my own approach to pagination.

I am going to start my project with the minimum. I will only be keeping the App and index CSS files and the App and index components. I will be using hooks so I will be importing the useState and useEffect hooks from React. First I will declare all the state variables that I need in the App component.
```react
const \[loading, setLoading\] = useState(true)

const \[characters, setCharacters\] = useState(\[\])

const \[currentPageUrl, setCurrentPageUrl\] = useState("https://rickandmortyapi.com/api/character")

const \[nextPageUrl, setNextPageUrl\] = useState()

const \[prevPageUrl, setPrevPageUrl\] = useState()

const \[pages, setPages\] = useState()
```
Now, I am going to use the Effect hook to fetch the data from the API. First, I will set the value of loading to true to make sure that a loading screen displays first. After the data arrives, the value can be set to false. The effect will run every time the current page URL changes. This is what that will look like.
```react
useEffect(() => {

  const url = currentPageUrl

  setLoading(true)

  const fetchData = async () => {

    const res = await fetch(url);

    const data = await res.json();

    setCharacters(data.results)

    setLoading(false);

    setNextPageUrl(data.info.next);

    setPrevPageUrl(data.info.prev);

    setPages(data.info.pages)

  }

  fetchData();

},\[currentPageUrl\])
```
Now that we have that I will create some functions that will be assigned to the buttons of our page navigation buttons. These functions will change the current page. I will be mapping the characters that we fetched to a variable called charList that will hold a list of components.
```javascript
function nextPage() {

setCurrentPageUrl(nextPageUrl)

}

function prevPage() {

setCurrentPageUrl(prevPageUrl)

}

function goToPage(num) {

setCurrentPageUrl(\`https://rickandmortyapi.com/api/character?page=${num}\`)

}

if (loading) return "Loading..."

const charList = characters.map(char => <Character key={Math.floor(Math.random() \* 10000)} name={char.name} img={char.image} />)
```
This is what the Character component will look like.
```javascript
import React from 'react'

const Character = ({ name, img }) => {

  return (

    <div className="character-card">

      <img src={img} alt="" />

      <div>{name}</div>

    </div>

  )

}

export default Character
```
We pass the name of the character and the image down as props. Now we need to create the buttons for the pagination feature. I will be doing this in its own component. We need to pass the nextPage, prevPage, and goToPage functions down as props to this component along with the number of pages.
```javascript
import React from 'react'

const Pagination = ({ nextPage, prevPage, goToPage, pages }) => {

  let pageButtons = \[\]

  for (let i = 1; i <= pages; i++) {

  pageButtons.push(<button key={i} onClick={() => goToPage(i)}>{i}</button>)

}

  return (

    <div>

      {prevPage && (<button onClick={prevPage}>Previous</button>)}

      {pageButtons}

      {nextPage && (<button onClick={nextPage}>Next</button>)}

    </div>

  )

}

export default Pagination
```
Here, I created a variable with an empty array assigned to it. Then, I am looping through the number of pages and creating a button for each page.

This will create all the buttons needed to navigate through all the pages. In the return statement, the previous and next buttons are conditionally rendered depending on whether their value is null or not. Now, we just need to add this component to our App component. I will show the pagination at the bottom and top of the page. It will look like this.
```javascript
return (

  <div className="App">

    <Pagination

    nextPage={nextPageUrl ? nextPage : null}

    prevPage={prevPageUrl ? prevPage : null}

    goToPage={goToPage}

    pages={pages}

  />

  <div className="char-cards">

    {charList}

  </div>

  <Pagination

    nextPage={nextPageUrl ? nextPage : null}

    prevPage={prevPageUrl ? prevPage : null}

    goToPage={goToPage}

    pages={pages}

  />

</div>

);
```
That is all that we need to get some pages using this API. It is a very simple way to implement pages if the API you are using already shows you the number of total pages available. Here is the final result.


![Final Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fskon3mmuab1zj6mehls.gif)

I had a lot of fun making trying this out. I hope that my approach will be helpful to some people. Happy coding!