Add, delete, and modify query parameters to the URL without refreshing or jumping page
Add, delete, or modify query parameters to the URL without refreshing current page or jumping to new page. The principle is pushing to the same route as the current one.
I provide 2 method to do it.
First method: modify URL
//123 -> 456
//www.xxx.com/123?a=2 -> www.xxx.com/456?a=2
let href = window.location.href; //www.xxx.com/123?a=2
let replaceId = '/' + 123;
window.history.replaceState({}, 'title', href.replace(/\/\d+/, replaceId));
Note: window.history.pushState pushing the route into the stack, and window.history.replaceState replacing the current route
Second method: Using History and location with react-router
1. Query current parameters:
const{ location } = this.props;
const { search } = location;
let queryStr = search.slice(1);//age=30&name=test
let queryArr = queryStr.split('&');//['age=30','name=test']
2. Add new parameters.
const{ history, location } = this.props;
const { search } = location;
if(search === ''){
history.push({
pathname: location.pathname,
search: 'name=test'
});
}else{
history.push({
pathname: location.pathname,
search: search + '&name=test'
});
}
3. Modify current parameters.
const{ history, location } = this.props;
const { search } = location;
// add/modify param
history.push({
pathname: location.pathname,
search: updateSearch('name', 'test1')
});
//search ?age=30&name=test2 -> ?age=30&name=test1
function updateSearch(targetKey,targetValue){
const { location } = this.props;
const { search } = location;
let queryStr = search.slice(1);//age=30&name=test2
let queryArr = queryStr.split('&');//['age=30','name=test2']
let targetIndex = -1;
queryArr.forEach((item,i) => {
let key = item.split('=')[0];
if(key === targetKey){
targetIndex = i;
}
});
// return original serach if param doesn't exist
if(targetIndex === -1){
return search;
}
let targetArr = queryArr[targetIndex].split('=');//['name','test2']
targetArr[1] = targetValue;
queryArr[targetIndex] = targetArr.join('=');//['name','test1']
return queryArr.join('&');
}
4. Remove parameters.
const{ history, location } = this.props;
history.push({
pathname: location.pathname,
search: deleteSearch('name')
});
// search ?age=30&name=test -> ?age=30
deleteSearch(targetKey){
const { location } = this.props;
const { search } = location;
let queryStr = search.slice(1);//age=30&name=test
let queryArr = queryStr.split('&');//['age=30','name=test']
let targetIndex = -1;
queryArr.forEach((item,i) => {
let key = item.split('=')[0];
if(key === targetKey){
targetIndex = i;
}
});
if(targetIndex === -1){
return search;
}
queryArr.splice(targetIndex,1);//['age=30']
return queryArr.join('&');
}
Hope it is helpful for you guys.