Archived student lesson
Add saved article list component
Part of End to End React with Prisma 2
Objective: Take an array of articles from the RSS feed and build an article list.
Now that we are fetching the articles, let’s build a list component for them. Since these RSS feeds can be quite long, sometimes with tens or hundreds of items though, let’s build in pagination from the start to keep track of it all. We could do this ourselves but there is a great react package called react-js-pagination that we will use.
npm install --save react-js-pagination
components/articleList.tsx
import { useState } from 'react'
import Pagination from 'react-js-pagination'
export const ArticleList = ({ articleList }: { articleList: any[] }) => {
const [currentPagination, setPagination] = useState({
currentPage: 1,
articlesPerPage: 8,
})
const { currentPage, articlesPerPage } = currentPagination
const indexOfLastArticle = currentPage * articlesPerPage
const indexOfFirstArticle = indexOfLastArticle - articlesPerPage
const currentArticles = articleList.slice(
indexOfFirstArticle,
indexOfLastArticle
)
console.log(currentArticles)
return (
<>
<h3 className="py-4 font-medium text-lg ">Articles</h3>
<div className="grid grid-cols-1 gap-4">
{currentArticles.map(({ feed, ...oneArticle }) => (
<p key={oneArticle.title}>{oneArticle.title}</p>
))}
<Pagination
innerClass="rounded py-2 px-2 flex"
itemClass="px-2"
activePage={currentPage}
itemCountPerPage={articlesPerPage}
totalItemsCount={articleList.length}
pageRangeDisplayed={5}
onChange={clickedNumber => {
setPagination(currState => ({
...currState,
currentPage: parseInt(clickedNumber),
}))
}}
/>
</div>
</>
)
}
We have the entire list of items in articleList that we pass in as a prop. We have a state which stores both the number of articles per page and the page that we are on. We calculate the index of the first and last articles on the list and perform a slice on articleList to get the chunk of articles that we are currently displaying. We then display that with using map.
The Pagination component nicely displays all of the page numbers and the forward and back buttons. As we click through the the pages, we store the page number on that state variable currentPage which controls how the list gets sliced to give us our segment of articles.
Then we need to use this component in the GenerateArticleList component:
components/articleList.tsx
import { ArticleList } from './articleList'
// rest of react component
if (loading) {
return <NotifyLoading />
}
if (error) {
return <NotifyError />
}
return <ArticleList articleList={data} />
Now we should see that a list of article titles. As we click between the different pages they should change. The titles should also change as we switch to different feeds or to the bundles page. Awesome!
Next we will create an actual article component.