David
David

Reputation: 341

How to remove one specific query parameter from URL in Next.js?

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.

Upvotes: 4

Views: 12732

Answers (4)

JamsDev
JamsDev

Reputation: 21

You can just remove it by deleting the property in router.query

delete router.query.search;
router.push(router);

Upvotes: 2

Jan Swart
Jan Swart

Reputation: 7231

To remove the query param completely from the url:

const { paramToRemove, ...routerQuery } = router.query;
router.replace({
  query: { ...routerQuery },
});

Upvotes: 8

juliomalves
juliomalves

Reputation: 50338

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.

Upvotes: 4

David
David

Reputation: 341

let queries = Object.assign({}, router.query);

delete queries.search;
return router.push(
      {
         pathname: `/`,
         query: queries
      },
      "",
      { scroll: false }
);

Upvotes: 0

Related Questions