1.0.4 • Published 5 years ago

use-search-params v1.0.4

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

useSearchParams

React Hook to use the URLSearchParams utility methods.

version minified size downloads build

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