Skip to content

Instantly share code, notes, and snippets.

@saadriazkhan
Last active December 7, 2021 01:33
Show Gist options
  • Save saadriazkhan/0fd78b7afab24497eb7f5ede7d72417b to your computer and use it in GitHub Desktop.
Save saadriazkhan/0fd78b7afab24497eb7f5ede7d72417b to your computer and use it in GitHub Desktop.
React useSearchParams hook in v6 to update query parameters
import { ChangeEvent } from 'react';
import { useSearchParams } from 'react-router-dom';
// Temporary key of my query parameter
const MY_QUERY_PARAMETER: string = 'myQueryParameter';
export const UpdateQueryParameters = (props: any) => {
// Hook which returns a tuple. First element is the current URLSearchParams object and second element is the function to take in the new URLSearchParams object alongside a configuration object to either replace the query parameters or not alongside state.
const [currentQueryParameters, setSearchParams] = useSearchParams();
const newQueryParameters : URLSearchParams = new URLSearchParams();
console.log(currentQueryParameters.get(MY_QUERY_PARAMETER));
const onInputValueChangeEventHandler: (event: ChangeEvent<HTMLInputElement>) => void =
({ target: { value }}: ChangeEvent<HTMLInputElement>): void => {
if (value)
newQueryParameters.set(MY_QUERY_PARAMETER, value);
setSearchParams(newQueryParameters);
}
return <input className="mt-2"
type="text"
onChange={onInputValueChangeEventHandler}
/>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment