@hotel-smarters/polyfill-search-params
v1.0.5
Published
A polyfill for URL search parameters manipulation in browsers
Downloads
57
Readme
Polyfill Search Params
A lightweight TypeScript library that provides a polyfill for URL search parameters manipulation in browsers. This library gives you a simple interface to get, set, and delete URL query parameters while maintaining browser history.
Features
- ⚛️ React Router Integration: Works seamlessly with react-router-dom
- 🚫 No useMemo Required: Direct URLSearchParams API without React hooks overhead
- 🔄 Automatic URL Sync: Updates browser URL automatically via react-router navigation
- 🔒 Type Safe: Written in TypeScript with full type definitions
- 📋 Full URLSearchParams API: Complete compatibility with native URLSearchParams
- 🔄 Iterator Support: Full support for forEach, keys(), values(), entries()
- 🪶 Lightweight: Minimal footprint with only react-router-dom dependency
- 🌐 Browser Compatible: Works in all modern browsers
- 📦 Multiple Formats: Supports CommonJS, ESM, and UMD formats
Installation
npm install @hotel-smarters/polyfill-search-paramsor
yarn add @hotel-smarters/polyfill-search-paramsUsage
Basic Usage
import { usePolyfillSearchParams } from '@hotel-smarters/polyfill-search-params';
const searchParams = usePolyfillSearchParams();
// Get a parameter value
const userId = searchParams.get('userId'); // returns string | null
// Set a parameter
searchParams.set('userId', '123');
// URL becomes: ...?userId=123
// Delete a parameter
searchParams.delete('userId');
// Parameter is removed from URL
// Get all parameters as string
const queryString = searchParams.toString();
// returns: "param1=value1¶m2=value2"React Router Integration (No useMemo needed!)
import React, { useState } from 'react';
import { usePolyfillSearchParams, createSearchParams } from '@hotel-smarters/polyfill-search-params';
function SearchComponent() {
const searchParams = usePolyfillSearchParams(); // Works with react-router-dom!
const [query, setQuery] = useState(searchParams.get('q') || '');
const handleSearch = (newQuery: string) => {
setQuery(newQuery);
if (newQuery) {
searchParams.set('q', newQuery); // Automatically updates URL via react-router
} else {
searchParams.delete('q');
}
};
return (
<div>
<input
type="text"
value={query}
onChange={(e) => handleSearch(e.target.value)}
placeholder="Search..."
/>
{/* Full URLSearchParams API support */}
<p>Current query: {searchParams.get('q') || 'none'}</p>
<p>Total params: {searchParams.size}</p>
<p>Has search: {searchParams.has('q') ? 'yes' : 'no'}</p>
{/* Iteration support */}
<ul>
{Array.from(searchParams.entries()).map(([key, value], index) => (
<li key={index}>{key}: {value}</li>
))}
</ul>
</div>
);
}Multiple Parameters
const searchParams = usePolyfillSearchParams();
// Set multiple parameters
searchParams.set('category', 'electronics');
searchParams.set('sort', 'price');
searchParams.set('page', '1');
// URL becomes: ...?category=electronics&sort=price&page=1
// Get parameters
const category = searchParams.get('category'); // "electronics"
const sort = searchParams.get('sort'); // "price"
const page = searchParams.get('page'); // "1"
// Remove a parameter
searchParams.delete('page');
// URL becomes: ...?category=electronics&sort=priceAPI
Hooks
usePolyfillSearchParams(): PolyfillURLSearchParams
The main hook for React Router integration. Returns a URLSearchParams instance that automatically syncs with react-router-dom navigation.
const searchParams = usePolyfillSearchParams();
searchParams.set('page', '2'); // Automatically updates URL via react-routeruseSearchParams(): PolyfillURLSearchParams
Returns a read-only URLSearchParams instance from the current location. Does not update the URL when modified.
const searchParams = useSearchParams();
const page = searchParams.get('page'); // Read current pagecreateSearchParams(init): PolyfillURLSearchParams
Utility function to create URLSearchParams from various inputs without any navigation integration.
const params = createSearchParams('?q=search&category=books');
const params2 = createSearchParams({ q: 'search', category: 'books' });
const params3 = createSearchParams([['q', 'search'], ['category', 'books']]);URLSearchParams Methods
The PolyfillURLSearchParams class implements the complete URLSearchParams interface:
get(key: string): string | null
Retrieves the value of the specified parameter.
- Parameters:
key: The parameter name to retrieve
- Returns: The parameter value as a string, or
nullif not found
set(key: string, value: string): void
Sets a parameter with the given key and value. Updates the browser URL.
- Parameters:
key: The parameter namevalue: The parameter value
delete(key: string): void
Removes the specified parameter from the URL.
- Parameters:
key: The parameter name to remove
toString(): string
Returns the current query string (without the leading ?).
- Returns: The query string as a string
Browser Support
This library works in all modern browsers that support:
window.locationwindow.history.replaceStateURLSearchParams(for URL encoding/decoding)
TypeScript
This library is written in TypeScript and includes type definitions. No additional @types packages are needed.
interface SearchParams {
get: (key: string) => string | null;
set: (key: string, value: string) => void;
delete: (key: string) => void;
toString: () => string;
}Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
1.0.0
- Initial release
- Basic search parameters manipulation
- TypeScript support
- Browser history integration
