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

@resourge/react-hook-table

v2.3.5

Published

react-hook-table is a hook with a set of tools to help to control a table. The hook provides control over sorting, pagination and filtering while updating the url search params to maintain consistency over page updates.

Downloads

41

Readme

React-hook-table

react-hook-table is a hook with a set of tools to help to control a table. The hook provides control over sorting, pagination and filtering while updating the url search params to maintain consistency over page updates.

Features

  • Uses @resourge/react-fetch
  • Saves filters, pagination and sorting on search params.
  • Provides a set of methods to help maintain and control a table pagination, sorting and filtering.
  • Provides methods to connect the navigation with other packages. (ex: react-router)
  • parseParams, parseSearch method's that extend URLSearchParams for own use.
  • useInfiniteLoading

Installation

Install using Yarn:

yarn add @resourge/react-hook-table

or NPM:

npm install @resourge/react-hook-table --save

(optional) Setup navigation

By default, @resourge/react-hook-table uses native javascript history to update the URL. This can create a problem with packages that don't connect to native javascript history, for example react-router.

To fix this do:

import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

// This functions connects the @resourge/react-hook-table to the react-router history
setDefaultNavigation(({ location }) => history.replace(location.path))

This connects react-router navigation with @resourge/react-hook-table

Usage

import React from 'react';
import { usePagination } from '@resourge/react-hook-table';

export default function List() {
  const {
    data: products, // Variable containing 'data'
	filter,
	error,
	isLoading,
	pagination,
	sort,

    fetch, // Method to re-fetch

	setFilter,
	changeItemsPerPage, 
	changePage, 
	changePagination, 
	changeTotalPages, 
	getPaginationHref,
	reset,
	resetPagination,
	setPaginationState,
	sortTable
  } = usePagination(
    async ({ pagination, sort, filter }) => {
      // fetch... use Http
        
      return await Promise.resolve({
        data: [
          { id: Math.random(), name: 'Apple' }
        ],
        totalItems: 10
      })
    },
    {
      initialState: [],
  	  /*
  	    // Default values
          filter,
  	    sort,
  	    pagination
  	  */
  	  deps: [] // Extra dependencies
    }
  )

  return (
    <table>
      <tbody>
        {
          products.map((product, index) => (
            <tr key={`${index}`}>
        	  <td>{ product.id } </td>
        	  <td>{ product.name } </td>
			</tr>
          ))
        }
      </tbody>
    </table>
  )
}

Config

| Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | fetchMethod | Promise | true | Method that return the Data and totalItems. | | config | { initialState: any, filter?: object, hash?: boolean, pagination?: PaginationCriteria, sort?: SortCriteria } & UseFetchConfig | true | Config to set initial/default filter, pagination and sort and initialState. When hash is true it will use Location hash instead of Location pathname to get `search. UseFetchConfig from @resourge/react-fetch. |

filter

Pagination Filters

pagination

Pagination per page and items per page

sort

Pagination sort

fetch

Method to refetch the current pagination

const {
  ...
  fetch
} = usePagination(...)

setFilter

Method to updates filters.

const {
  ...
  setFilter
} = usePagination(...)

changeItemsPerPage

Changes items per page

const {
  ...
  changeItemsPerPage
} = usePagination(...)

changePage

Changes current page

const {
  ...
  changePage
} = usePagination(...)

changePagination

Changes both current page and items per page

const {
  ...
  changePagination
} = usePagination(...)

changeTotalPages

Changes total number of pages using total number of items Note: It doesn't trigger render.

const {
  ...
  changeTotalPages
} = usePagination(...)

getPaginationHref

Builds href for use on navigation. (usually used with pagination component)

const {
  ...
  getPaginationHref
} = usePagination(...)

reset

Resets the pagination, sort and/or filter.

const {
  ...
  reset
} = usePagination(...)

resetPagination

Resets pagination to initial/default values

const {
  ...
  resetPagination
} = usePagination(...)

setPaginationState

To set pagination state manually

const {
  ...
  setPaginationState
} = usePagination(...)

sortTable

Changes which column to order asc/desc.

const {
  ...
  sortTable
} = usePagination(...)

useInfiniteLoading

Usage

import React from 'react';
import { useInfiniteLoading, RefreshControl } from '@resourge/react-hook-table';

export default function List() {
  const {
    data: products, // Variable containing 'data'
	filter,
	error,
	isLoading,
	sort,

	context,
	isLast,
	isLastIncomplete,

	loadMore,
	preload,
    fetch, // Method to re-fetch

	setFilter,
	changeItemsPerPage, 
	reset,
	setPaginationState,
	sortTable
  } = useInfiniteLoading(
    async ({ pagination, sort, filter }) => {
      // fetch... use Http
        
      return await Promise.resolve({
        data: [
          { id: Math.random(), name: 'Apple' }
        ],
        totalItems: 10
      })
    },
    {
      initialState: [],
  	  /*
  	    // Default values
          filter,
  	    sort,
  	    pagination
  	  */
  	  deps: [] // Extra dependencies
    }
  )

  return (
    <table>
      <tbody>
        {
          products.map((product, index) => (
            <tr key={`${index}`}>
        	  <td>{ product.id } </td>
        	  <td>{ product.name } </td>
			</tr>
          ))
        }
		<tr>
		  <td>
            <RefreshControl 
              context={context}
              renderComponent={({ isLastIncomplete, onClick }) => (
                !isLastIncomplete 
                  ? (
                    <button
                     disabled={isLoading}
                     onClick={onClick}
                    >Get more</button>
                  ) : null
              )}
            />
		  </td>
		</tr>
      </tbody>
    </table>
  )
}

context

Contains all the from useInfiniteLoading. (Works with RefreshControl)

const {
  ...
  loadMore
} = usePagination(...)

isLast

If is last 'page'

const {
  ...
  isLast
} = usePagination(...)

isLastIncomplete

If last 'page' is incomplete (itemPerPage 10 but the last page got less than 10)

const {
  ...
  isLastIncomplete
} = usePagination(...)

loadMore

Method to load more 'pages'

const {
  ...
  loadMore
} = usePagination(...)

preload

Method to preload the next 'page

const {
  ...
  preload
} = usePagination(...)

useInfiniteScrollRestoration

Method to restore scroll in infinite scroll.

// useAction will probably be from a navigation/router package
// Ex: import { useAction } from '@resourge/react-router';
const action = useAction();
// 'action' must be 'pop' for restoration to work;
const [scrollRestoration, ref] = useInfiniteScrollRestoration(action);
const {} = useInfiniteLoading(
  ..., 
  {
    initialState: [],
    scrollRestoration
  }
);

RefreshControl

Component to help useInfiniteScroll control the scroll.

import React from 'react';
import { useInfiniteLoading, RefreshControl } from '@resourge/react-hook-table';

export default function List() {
  const {
    //...
	context,

  } = useInfiniteLoading(
    async ({ pagination, sort, filter }) => {
      // fetch... use Http
        
      return await Promise.resolve({
        data: [
          { id: Math.random(), name: 'Apple' }
        ],
        totalItems: 10
      })
    },
    {
      initialState: [],
  	  deps: [] // Extra dependencies
    }
  )

  return (
    <>
      ...
      <RefreshControl 
        context={context}
        renderComponent={({ isLastIncomplete, onClick }) => (
          !isLastIncomplete 
          ? (
            <button
              disabled={isLoading}
              onClick={onClick}
            >Get more</button>
          ) : null
        )}
      />
    </>
  )
}

parseParams

Params object into search path

import { parseParams } from '@resourge/react-hook-table';

parseParams({
  productId: 10,
  productName: 'Apple'
})
// ?productId=10&productName=Apple

parseSearch

Converts search string into object.

import { parseSearch } from '@resourge/react-hook-table';

parseSearch('?productId=10&productName=Apple')
// {
//   productId: 10,
//   productName: 'Apple'
// }

License

MIT Licensed.