http://localhost:3000/?search=test&type=abc&category=xyz
After I search for test (among with type and category), the URL changes to the URL above.
return router.push(
{
pathname: `/`,
query: {
// something to do here...
},
},
"",
{ scroll: false }
);
Next, I have an onClick
with this router.push
.
I would like to remove ONLY the search query and keep the type and category queries. How is it possible? The documentation doesn't mention anything about this.
http://localhost:3000/?search=test&type=abc&category=xyz
After I search for test (among with type and category), the URL changes to the URL above.
return router.push(
{
pathname: `/`,
query: {
// something to do here...
},
},
"",
{ scroll: false }
);
Next, I have an onClick
with this router.push
.
I would like to remove ONLY the search query and keep the type and category queries. How is it possible? The documentation doesn't mention anything about this.
Share Improve this question edited May 11, 2022 at 20:09 juliomalves 50.3k23 gold badges177 silver badges168 bronze badges asked May 10, 2022 at 10:46 DavidDavid 3411 gold badge10 silver badges27 bronze badges4 Answers
Reset to default 8To remove the query param completely from the url:
const { paramToRemove, ...routerQuery } = router.query;
router.replace({
query: { ...routerQuery },
});
You can call router.push
with the current query string, but omitting the search
parameter.
const params = new URLSearchParams(router.query);
params.delete('search');
const queryString = params.toString();
const path = `/${queryString ? `?${queryString}` : ''}`;
router.push(path, '', { scroll: false });
Given that you're currently at /?search=test&type=abc&category=xyz
, the above will route you to /?type=abc&category=xyz
. This will also handle scenarios where the type
and category
query parameters aren't present.
You can just remove it by deleting the property in router.query
delete router.query.search;
router.push(router);
let queries = Object.assign({}, router.query);
delete queries.search;
return router.push(
{
pathname: `/`,
query: queries
},
"",
{ scroll: false }
);