2.1.1 • Published 5 months ago

react-use-pagination-hook v2.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

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

OptionTypeDescription
numOfPagenumberThe 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.
totalPagenumber?(optional, default:0)The initial value of the total number of pages.
initialPagenumber?(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

NameTypeDescription
pageListnumber[]The array that represents the current page bar, If the total number of pages is 0, initialPage is returned.
currentPagenumberThis 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) => voidSet the total number of pages to be used when initializing the page count in response to the server side.
setPage(page: number) => voidUpdate 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() => voidGo to the previous page (currentPage decreases by -1).
goNext() => voidGo to the next page. (currentPage increases by +1)
goBeforeSection() => voidGo to the previous section, and the page list will change.
goNextSection() => voidGo to the next section, and the page list will change.
goFirstSection() => voidGo to the first section, and the page list will change.
goLastSection() => voidGo to the last section, and the page list will change.
hasNextSectionbooleanReturns whether the next section exists
hasBeforeSectionbooleanReturns 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 <jeongyunniim@gmail.com>. This project is MIT licensed.

Bug reporting

Please use issue to report bugs