npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-server-pagination

v1.0.0

Published

Pagination in next.js server component using just one function

Downloads

2

Readme

next-server-pagination

license npm version

Add pagination to your next.js app with one function. The library works with React Server Components, so you can limit how much data you read from database and send to client. Page navigation is fully customizable.

Installation

npm install next-server-pagination

Usage

Just wrap your server component with withPagination and pass a function that returns number (or a Promise<number>) of elements as a second argument. The third, optional argument is a settings object.

Then you can access page property inside your component and use it to limit data you read from database. Page property is of type PageData.

IMPORTANT! This library uses searchParams to store page number and other data. If you use withPagination outside of page.tsx, you need to pass searchParams manually as a prop. (see non page component example)

To add page navigation, create a client component and call usePagination hook. It returns functions like next, previous (see UsePagination type)

Example

In this example data is a simple array, but you can for example use prisma with skip and take to limit data you read from database.

page.tsx

import { withPagination, PageData } from 'next-server-pagination';
import { data } from './data';
import PageSwitcher from './pageSwitcher';

async function getDataLength() {
    return data.length;
}

async function getData(start: number, end: number) {
    return data.slice(start, end + 1);
}

async function Page({ page }: { page: PageData }) {
    // access page data ^ in your component
    const data = await getData(page.firstElement, page.lastElement);

    return (
        <>
            <div className="grid grid-cols-4 gap-4 mx-auto max-w-4xl p-2 my-4">
                {data.map((element, index) => (
                    <div
                        className="rounded-lg border border-slate-400 p-4 text-center"
                        key={index}
                    >
                        {element}
                    </div>
                ))}
            </div>
            <PageSwitcher />
        </>
    );
}

export default withPagination(Page, getDataLength);
//    just add ^^^^

pageSwitcher.tsx

'use client';

import { usePagination } from 'next-server-pagination';

export default function PageSwitcher() {
    const page = usePagination();

    return (
        <div className="flex items-center justify-center">
            <button
                onClick={page.previous}
                disabled={page.isFirst}
                className="rounded-md py-1 px-2 border border-black"
            >
                &lt;
            </button>
            <p className="mx-4">
                {page.current} / {page.total}
            </p>
            <button
                onClick={page.next}
                disabled={page.isLast}
                className="rounded-md py-1 px-2 border border-black"
            >
                &gt;
            </button>
        </div>
    );
}

Types

If you want to add add type to your component's props, you can either

  • type page props as PageData
import { PageData } from 'next-server-pagination';

function Page({ page }: { page: PageData }) {
    ...
}
export default withPagination(Page, getDataLength);
  • whole props object as WithPaginationProps (then you can also use searchParams)
import { WithPaginationProps } from 'next-server-pagination';

function Page({ page }: WithPaginationProps) {
    ...
}
export default withPagination(Page, getDataLength);
  • or declare a component inside withPagination and props will be infered automatically
import { withPagination } from 'next-server-pagination';

export default withPagination(
    function Page({ page }) {
        ...
    },
    getDataLength
);

PageData

| Property | Type | Description | | -------------- | -------- | -------------------------------------------------------------------------------------- | | current | number | Index of the page that user is currently on. It is an integer between 1 and total. | | total | number | Total number of pages. | | size | number | Number of elements per page. | | firstElement | number | Index of the first element on the page. | | lastElement | number | Index of the last element on the page. |

UsePagination

Includes all properties from PageData and:

| Property | Type | Description | | ---------- | ------------------------ | -------------------------------------- | | isFirst | boolean | Whether the user is on the first page. | | isLast | boolean | Whether the user is on the last page. | | next | () => void | Switches to the next page. | | previous | () => void | Switches to the previous page. | | setPage | (page: number) => void | Switches to the specified page. | | setSize | (size: number) => void | Sets the number of elements per page. |

PaginationSettings

| Property | Type | Default | Description | | ------------- | -------- | ------- | ---------------------------------------------------------------------------------------- | | defaultSize | number | 20 | Default number of elements per page. It is used if size is not provided in search params |