use-search-params
v1.0.4
Published
A React Hook to use the URLSearchParams utility methods
Downloads
24
Maintainers
Readme
useSearchParams
React Hook to use the URLSearchParams utility methods.
Install
npm
npm install use-search-params --save
yarn
yarn add use-search-params
Usage
The hook returns the current url query string value together with the URLSearchParams methods to manipulate it.
import useSearchParams from 'use-search-params';
const MyComponent = () => {
const [
queryString,
{ append, entries, get, getAll, has, keys, remove, set, sort, values }
] = useSearchParams();
const entries = entries();
const keys = keys();
const values = values();
const value = get('key');
const allValues = getAll('key');
const hasKey = has('key');
return (
<div>
<p>Query string: {queryString}</p>
<button onClick={() => append('key', 'value')}>
Append
</button>
<button onClick={() => remove('key')}>Remove</button>
<button onClick={() => set('key', 'value')}>Set</button>
<button onClick={() => sort()}>Sort</button>
<button
onClick={() => {
window.location.search = queryString;
}}
>
Set new location with generated queryString
</button>
</div>
);
}
Learn more
This hook uses the URLSearchParams api
License
MIT