Implementing Effective Pagination in Your Blog: A Blueprint

Explore how to enhance user experience on your blog through efficient pagination and article fetching logic. Discover the transformation brought by the introduction of the PAGE_LIMIT constant, the getArticles function with pagination, and other improvements.

Make Your Blog More User-Friendly with Pagination

Running a blog with tons of articles? Loading all that content on a single page can be a nightmare! It makes your blog look cluttered, slower to load, and hard to navigate. But fear not, dear reader—pagination is here to save the day!

Why Pagination Rocks

Pagination divides your web content into smaller, separate pages.

  • Better Navigation: Users can easily flip through pages.
  • Faster Load Times: No more waiting ages for all articles to load.
  • Improved User Experience: A less cluttered, more organized blog.

Introducing the PAGE_LIMIT Constant and getArticles Function

To implement pagination, we brought in the PAGE_LIMIT constant. Here’s what changed:

  • Added PAGE_LIMIT: Defines the number of articles per page.
  • Updated getArticles Function: Handles pagination logic using the page and limit parameters.
  • Enhanced Home Component: Uses searchParams for pagination.
  • Added Navigation Buttons: Stylish 'Previous' and 'Next' buttons for easy navigation.

How It Works

  1. Define PAGE_LIMIT: Sets a limit to the number of articles per page.
  2. Modify getArticles Function: Parses page and limit parameters to read article directories and paginate results.
  3. Update Home Component: Integrates searchParams and includes navigation buttons.
  4. Improve Layout and Styling: Visual and functional enhancements for a better user experience.

Technical Breakdown

Here’s a snippet of the code that does all this magic:

const PAGE_LIMIT = 5;

const getArticles = async (page = 1, limit = PAGE_LIMIT) => {
  const articlesDirectory = path.join(process.cwd(), 'src/articles');
  const files = await fs.promises.readdir(articlesDirectory);

  // Calculate pagination values
  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;
  const paginatedFiles = files.slice(startIndex, endIndex);

  const articles = await Promise.all(paginatedFiles.map(async (filename) => {
    const filePath = path.join(articlesDirectory, filename);
    const markdownWithMetadata = await fs.promises.readFile(filePath, 'utf-8');
    const { data: frontMatter } = matter(markdownWithMetadata);
    const slug = filename.split('.')[0];
    return {
      ...frontMatter,
      slug,
      href: `/article/${slug}`,
    };
  }));

  return {
    articles,
    currentPage: page,
    totalPages: Math.ceil(files.length / limit),
  };
};

const Home = async ({ params, searchParams }: HomeProps) => {
  const page = searchParams.page ? parseInt(searchParams.page as string, PAGE_LIMIT) : 1;
  const { articles, currentPage, totalPages } = await getArticles(page);
  const hasPrev = currentPage > 1;
  const hasNext = currentPage < totalPages;
  const plasmicData = await PLASMIC.fetchComponentData({
    projectId: 'projectId',
    name: 'componentName',
  });
  const compMeta = plasmicData.entryCompMetas[0];

  return (
    <>
      <PlasmicClientRootProvider
        prefetchedData={plasmicData}
        prefetchedQueryData={plasmicData.prefetchedQueryData}
      >
        <PlasmicComponent component={compMeta.name} componentProps={
          {
            articles: articles.map(article => ({
              title: article.title,
              href: article.href,
              slug: article.slug,
            })),
            actionItems: <div>
              <div>
                {hasPrev && <PlasmicComponent component='Button' componentProps={
                  {
                    title: 'Previous',
                    link: `?page=${currentPage - 1}`,
                    children: <span>&larr; Previous</span>,
                  } as ButtonProps} />}
                {hasNext && <PlasmicComponent component='Button' componentProps={
                  {
                    title: 'Next',
                    link: `?page=${currentPage + 1}`,
                    children: <span>Next &rarr;</span>
                  } as ButtonProps} />}
              </div>
              <PlasmicComponent component='Button' componentProps={
                {
                  link: '/',
                  children: <span>&larr; Back home</span>
                } as ButtonProps} />
            </div>
          }
        } />
      </PlasmicClientRootProvider>
    </>
  );
};

export default Home;

Final Thoughts

A few targeted changes like implementing pagination can dramatically improve the performance and user experience of your blog. Pagination isn't just a feature; it's a nifty little tool that can make your site more efficient, user-friendly, and appealing. So go ahead, give it a try, and watch your blog flourish!

← Back to posts

We use cookies to improve your experience and analyze our traffic. By using our site, you consent to our use of cookies. You can manage your preferences below: