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

react-use-pagination-hook

v2.1.1

Published

Lightweight headless UI pagination hook

Downloads

355

Readme

Install

$ npm install --save react-use-pagination-hook

or

$ yarn add react-use-pagination-hook

Features

  • ⚙️ Completely unstyled, You only need to provide UI controls.
  • ✅ Only State hooks & callbacks, compatible with other libraries.
  • ✨ Provides several different methods for page navigation, such as section-by-section navigation.

Demo

https://je0ngyun.github.io/react-use-pagination-hook

Usage

const App = () => {
  const {
    pageList,
    goNextSection,
    goBeforeSection,
    goFirstSection,
    goLastSection,
    goNext,
    goBefore,
    setTotalPage,
    setPage,
    currentPage,
  } = usePagination({ numOfPage: 5, totalPage: 15 })

  return (
    <div className="App">
      <main className="container">
        <button onClick={() => goFirstSection()}>{'First'}</button>
        <button onClick={() => goBeforeSection()}>{'<<'}</button>
        <button onClick={() => goBefore()}>{'<'}</button>
        <ul className="pages">
          {pageList.map((page) => (
            <li
              onClick={() => setPage(page)}
              className={currentPage === page ? 'selected' : ''}
              key={page}
            >
              {page}
            </li>
          ))}
        </ul>
        <button onClick={() => goNext()}>{'>'}</button>
        <button onClick={() => goNextSection()}>{'>>'}</button>
        <button onClick={() => goLastSection()}>{'Last'}</button>
      </main>
    </div>
  )
}

export default App

API

Props

| Option | Type | Description | | ------------ | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | numOfPage | number | The number of pages to be displayed on the pagination bar. If the number of pages to display at once in the pagination bar is greater than the total number of pages, the page list will be initialized with the total number of pages. | | totalPage | number?(optional, default:0) | The initial value of the total number of pages. | | initialPage | number?(optional, default:1) | The initial value of the current page. | | onPageChange | (page: number) => void? (optional) | Callback that is triggered every time a page is changed. |

Hook return value

| Name | Type | Description | | ---------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | pageList | number[] | The array that represents the current page bar, If the total number of pages is 0, [initialPage] is returned. | | currentPage | number | This is the currently selected page, with the initial value of the initial page props. If the total number of pages is 0, initialPage is returned. | | setTotalPage | (tatalPage: number) => void | Set the total number of pages to be used when initializing the page count in response to the server side. | | setPage | (page: number) => void | Update the currently selected page number in the pageList, If you try to set a value that is not in the page list array, an error is thrown. | | goBefore | () => void | Go to the previous page (currentPage decreases by -1). | | goNext | () => void | Go to the next page. (currentPage increases by +1) | | goBeforeSection | () => void | Go to the previous section, and the page list will change. | | goNextSection | () => void | Go to the next section, and the page list will change. | | goFirstSection | () => void | Go to the first section, and the page list will change. | | goLastSection | () => void | Go to the last section, and the page list will change. | | hasNextSection | boolean | Returns whether the next section exists | | hasBeforeSection | boolean | Returns whether the before section exists |

With React-Query

const numOfPage = 5
const limit = 10

interface FetchPages {
  (page: number): Promise<{ results: { name: string }[]; count: number }>
}

const fetchPages: FetchPages = async (page: number) => {
  try {
    const res = await fetch(`https://swapi.dev/api/people/?page=${page}`)
    if (!res.ok) throw new Error('Error')
    return res.json()
  } catch (err) {
    console.log(err)
  }
}

const LandingPage = () => {
  const {
    pageList,
    goNextSection,
    goBeforeSection,
    goFirstSection,
    goLastSection,
    goNext,
    goBefore,
    setTotalPage,
    setPage,
    currentPage,
  } = usePagination({ numOfPage })

  const { data } = useQuery(
    ['pagination', currentPage],
    () => fetchPages(currentPage),
    {
      onSuccess: (data) => {
        // Reinitialize the total page state using the server-side response result
        // The API used in the example was calculated because it returns the total number of items.
        setTotalPage(
          data.count % limit ? data.count / limit + 1 : data.count / limit
        )
        // setTotalPage(data.totalPage)
      },
    }
  )

  return (
    <>
      <ul className="items">
        {!data && <li>loading...</li>}
        {data?.results.map(({ name }, idx) => (
          <li key={idx}>{name}</li>
        ))}
      </ul>
      <main className="container">
        <button onClick={() => goFirstSection()}>{'First'}</button>
        <button onClick={() => goBeforeSection()}>{'<<'}</button>
        <button onClick={() => goBefore()}>{'<'}</button>
        <ul className="pages" aria-labelledby="pages">
          {pageList.map((page) => (
            <li
              onClick={() => setPage(page)}
              className={currentPage === page ? 'selected' : ''}
              key={page}
            >
              {page}
            </li>
          ))}
        </ul>
        <button onClick={() => goNext()}>{'>'}</button>
        <button onClick={() => goNextSection()}>{'>>'}</button>
        <button onClick={() => goLastSection()}>{'Last'}</button>
      </main>
    </>
  )
}

export default LandingPage

Result

With SearchParams

With the addition of the "initialPage" and "onPageChange" features in version 2.1.0, it is now possible to seamlessly integrate them with search parameters.

// Example of using the useSearchParams hook from react-router-dom

const usePageParam = () => {
  const [params, setParams] = useSearchParams()

  const pageParam = params.get('page') || 1

  const setPageParam = (page) => {
    params.set('page', page)
    setParams(params)
  }

  return [pageParam, setPageParam]
}

const App = () => {
  const [pageParam, setPageParam] = usePageParam()

  const {
    pageList,
    goNextSection,
    goBeforeSection,
    goFirstSection,
    goLastSection,
    goNext,
    goBefore,
    setTotalPage,
    setPage,
    currentPage,
  } = usePagination({
    numOfPage: 5,
    totalPage: 15,
    initialPage: pageParam,
    onPageChange: (page) => setPageParam(page),
  })

  return (
    <div className="App">
      <main className="container">
        <button onClick={() => goFirstSection()}>{'First'}</button>
        <button onClick={() => goBeforeSection()}>{'<<'}</button>
        <button onClick={() => goBefore()}>{'<'}</button>
        <ul className="pages">
          {pageList.map((page) => (
            <li
              onClick={() => setPage(page)}
              className={currentPage === page ? 'selected' : ''}
              key={page}
            >
              {page}
            </li>
          ))}
        </ul>
        <button onClick={() => goNext()}>{'>'}</button>
        <button onClick={() => goNextSection()}>{'>>'}</button>
        <button onClick={() => goLastSection()}>{'Last'}</button>
      </main>
    </div>
  )
}

export default App

License

Copyright © 2022 jeongyun [email protected]. This project is MIT licensed.

Bug reporting

Please use issue to report bugs