I am trying to update only one query param key-value on button click using react-router (v5).
const btnClickHandler = () =>{
history.push({ search: 'popup=false' });
}
I want this code to update the url from:
https://base-url.com/?popup=true&checked=true
to:
https://base-url.com/?popup=false&checked=true
but instead, it replaces the whole search to:
https://base-url.com/?popup=false
Basically, instead of replacing all the query param key value, how can I replace only one?
You need to merge the query params yourself before updating them. You could use query-string
(https://www.npmjs.com/package/query-string) library to make your job easier.
import qs from 'query-string';
const Component = ({ location}) => {
const btnClickHandler = () =>{
const queryParams = qs.parse(location.search);
const newQueries = { ...queryParams, popup:false};
history.push({ search: qa.stringify(newQueries) });
}
}
With the version 6 of react-router-dom, you could:
const [searchParams, setSearchParams] = useSearchParams();
let updatedSearchParams = new URLSearchParams(searchParams.toString());
updatedSearchParams.set('operation', 'edit');
setSearchParams(updatedSearchParams.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With