useQueryParams
A custom hook that provides functionalities for managing query parameters in the URL.
⚠️
This hook has a dependency on useHistory.
Add hook
Create a file use-query-params.ts
and copy & paste from useQueryParams
Hook
import { useHistory } from './use-history'
export const useQueryParams = () => {
const history = useHistory()
const urlParams = new URLSearchParams(window.location.search)
const get = (param: string) => {
for (const [key, value] of urlParams) {
if (param === key) {
return value
}
}
}
const getAll = () => {
const keys = new Map()
for (const [key, value] of urlParams) {
keys.set(key, value)
}
return keys
}
const set = (key: string, value: string | number) => {
const isFound = getAll().has(key)
if (isFound) {
urlParams.set(key, value as string)
} else {
urlParams.append(key, value as string)
}
const newRelativePathQuery = window.location.pathname + '?' + urlParams.toString()
history.push(newRelativePathQuery)
}
const setEncoded = (obj: { [s: string]: string | number } | ArrayLike<string>) => {
const encodedParams = new URLSearchParams()
for (const [key, value] of Object.entries(obj)) {
encodedParams.append(key, value as string)
}
const newRelativePathQuery = window.location.pathname + '?' + encodedParams.toString()
history.push(newRelativePathQuery)
}
return { urlParams: getAll(), get, set, setEncoded }
}
Usage
import React from 'react';
import { useQueryParams } from './use-query-params';
function ExampleComponent() {
const { queryParams, get, set, setEncoded } = useQueryParams();
// Get a specific query parameter
const paramValue = get('name');
// Set a query parameter
const handleClick = () => {
set('age', 30);
};
// Set multiple query parameters
const handleSetMultiple = () => {
setEncoded({ language: 'arabic', nationality: 'algerian' });
};
return (
<div>
<h1>Query Parameters Example</h1>
<p>Value of paramName: {paramValue}</p>
<button onClick={handleClick}>Set newParam to 'newValue'</button>
<button onClick={handleSetMultiple}>Set multiple parameters</button>
<h2>Current Query Parameters:</h2>
<ul>
{Array.from(queryParams).map(([key, value]) => (
<li key={key}>
{key}: {value}
</li>
))}
</ul>
</div>
);
}
export default ExampleComponent;
API
Returns
Name | Description |
---|---|
queryParams | A Map representing the current state of query parameters in the URL. |
get(param: string): string | Retrieves the value of a specific query parameter from the URL. |
set(key: string, value: string | number): void | Sets the value of a query parameter in the URL. |
setEncoded(obj: { [s: string]: string | number } | ArrayLike<string>): void | Sets the query parameters in the URL using an object or an array-like structure. |