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

@aboutbits/react-pagination

v3.1.2

Published

Pagination hooks for React

Downloads

339

Readme

React Pagination

npm package license

Query hooks for React with first-class support for TypeScript! Writing and reading the query, attached to the browser URL or in-memory, made easy!

Table of content

Usage

Install the package:

npm install @aboutbits/react-pagination

There are a variety of entry points from which to import the hooks useQuery, usePagination and useQueryAndPagination:

  • For the Next.js router:
    • @aboutbits/react-pagination/next-router
    • @aboutbits/react-pagination/next-router/zod
  • For React Router:
    • @aboutbits/react-pagination/react-router
    • @aboutbits/react-pagination/react-router/zod
  • For an in-memory router that does not modify the browser history:
    • @aboutbits/react-pagination/in-memory
    • @aboutbits/react-pagination/in-memory/zod

The hooks exported from @aboutbits/react-pagination/*/zod are more convenient when using zod for the validation of the query.

useQueryAndPagination merges the functionality of useQuery and usePagination. Changing the query resets the page, but changing the page does not reset the query.

Some examples follow, but we recommend having a look at the type definitions for more details about the API.

Example usage with Next.js

import { Query } from '@aboutbits/react-pagination/dist/engine'
import { useQueryAndPagination } from '@aboutbits/react-pagination/dist/routers/nextRouter'

const users = ['Alex', 'Simon', 'Natan', 'Nadia', 'Moritz', 'Marie']

const parseSearch = (query: Query) => {
  for (const [key, value] of Object.entries(query)) {
    if (key === 'search' && !Array.isArray(value)) {
      return { search: value }
    }
  }
  return {}
}

export function UserList() {
  const { page, size, query, setQuery, setPage, resetQuery } =
    useQueryAndPagination(parseSearch, { search: '' })

  return (
    <div>
      <input
        value={query.search}
        onChange={(event) => setQuery({ search: event.target.value })}
      />
      <button onClick={() => resetQuery()}>Clear Input</button>
      <select
        value={page}
        onChange={(event) => setPage(parseInt(event.target.value))}
      >
        <option value="0">First Page</option>
        <option value="1">Second Page</option>
      </select>
      <ul>
        {users
          .filter((user) =>
            user.toLowerCase().startsWith(query.search.toLowerCase()),
          )
          .slice(page * size, (page + 1) * size)
          .map((user) => (
            <li key={user}>{user}</li>
          ))}
      </ul>
    </div>
  )
}

Example usage with Next.js, zod and no default query

Notice that we let zod take a string and then coerce it to a number. If the coercion fails, we do not stop the whole parsing, but default the property to undefined. This allows us to still use departmentId if it is defined while userId is not and vice versa.

import { useQueryAndPagination } from '@aboutbits/react-pagination/dist/zod/routers/nextRouter'
import { z } from 'zod'

export function Component() {
  const { page, size, query, setQuery, setPage, resetQuery } =
    useQueryAndPagination(
      z.object({
        departmentId: z
          .string()
          .pipe(z.coerce.number().optional())
          .catch(undefined),
        userId: z.string().pipe(z.coerce.number().optional()).catch(undefined),
      }),
    )

  // ... do something
}

Example usage with React Router and zod

import { useQueryAndPagination } from '@aboutbits/react-pagination/dist/zod/routers/reactRouter'
import { z } from 'zod'

const userSchema = z.object({
  name: z.string(),
  // The input to the parser is going to be a string.
  // We try to convert it to a number and default to undefined if the parsing fails.
  // This continues the parsing of the remaining query.
  // Another possibility would be to not catch errors, which would cancel the entire parsing
  // if "age" cannot be converted to a number.
  age: z.string().pipe(z.coerce.number().optional()).catch(undefined),
})

const users = [
  { name: 'Alex', age: 10 },
  { name: 'Simon', age: 24 },
  { name: 'Natan', age: 88 },
  { name: 'Nadia', age: 42 },
  { name: 'Moritz', age: 35 },
  { name: 'Marie', age: 17 },
]

export function UserList() {
  const { page, size, query, setQuery, setPage, resetQuery } =
    useQueryAndPagination:
      userSchema,
      { name: '', age: 0 },
      {
        page: 0,
        size: 4,
      },
    )

  return (
    <div>
      <div>
        Name:
        <input
          value={query.name}
          onChange={(event) => setQuery({ name: event.target.value })}
        />
      </div>
      <div>
        Minimum age:
        <input
          value={query.age}
          onChange={(event) => {
            const value = event.target.value
            const parsed = parseInt(value)
            if (!isNaN(parsed)) {
              setQuery({ age: parsed })
            }
          }}
        />
      </div>
      <button onClick={() => resetQuery()}>Clear Input</button>
      <select
        value={page}
        onChange={(event) => setPage(parseInt(event.target.value))}
      >
        <option value="0">First Page</option>
        <option value="1">Second Page</option>
      </select>
      <ul>
        {users
          .filter(
            (user) =>
              user.name.toLowerCase().startsWith(query.name.toLowerCase()) &&
              user.age >= query.age,
          )
          .slice(page * size, (page + 1) * size)
          .map((user) => (
            <li key={user.name}>{user.name}</li>
          ))}
      </ul>
    </div>
  )
}

Build & Publish

To publish the package commit all changes and push them to main. Then run one of the following commands locally:

npm version patch
npm version minor
npm version major

Information

AboutBits is a company based in South Tyrol, Italy. You can find more information about us on our website.

Support

For support, please contact [email protected].

Credits

License

The MIT License (MIT). Please see the license file for more information.