React hook to manage URL query filters and keep them in sync with the browser URL.
npm install @drawbotics/use-filters| Package | Version |
|---|---|
react |
^16.0.0 |
history |
^5.3.0 |
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);
}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',
});| 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 |
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.
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 |
UNLICENSED