Skip to content

Drawbotics/drawbotics-use-filters

Repository files navigation

@drawbotics/use-filters

React hook to manage URL query filters and keep them in sync with the browser URL.

Installation

npm install @drawbotics/use-filters

Peer Dependencies

Package Version
react ^16.0.0
history ^5.3.0

Usage

import { useFilters } from '@drawbotics/use-filters';

function MyComponent() {
  const { status, category } = useFilters(location, navigate, ['status', 'category']);

  // read a single value
  console.log(status.value); // => "active"

  // read all values for a key
  console.log(category.values); // => ["furniture", "lighting"]

  // set a value
  status.set('inactive');

  // set multiple values
  category.set(['furniture', 'lighting']);

  // clear a filter
  status.set(null);
}

With Persistence

Filters can be persisted to localStorage so they are restored when the user revisits the page:

const filters = useFilters(location, navigate, ['status', 'category'], {
  persistenceKey: 'my-page-filters',
});

API

useFilters(location, navigate, keys, options?)

Parameter Type Description
location History.Location Current location object from your router
navigate Navigate Navigation function from your router
keys string[] List of query parameter keys to manage
options { persistenceKey } Optional. Enables localStorage persistence

Filter

Each key returns a Filter object:

Property Type Description
value string | undefined First value for the key
values string[] | undefined All values for the key
set (value: string | string[] | null) => void Set, replace, or clear the filter

Calling set(null) removes the filter from the URL. Passing an array sets multiple values for the same key.

Development

npm install
npm test
npm run build
Script Description
npm run clean Remove build artifacts
npm run build Compile TypeScript
npm run build:watch Compile in watch mode
npm test Run tests
npm run test:watch Run tests in watch mode

License

UNLICENSED

About

Hook to manage filter values and keep them in sync with the url

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors