Home > Software design >  React-router: is there a way to use push from history to append a query string after this current pa
React-router: is there a way to use push from history to append a query string after this current pa

Time:02-16

my current URL is /foo and I want to add a query string to it i.e. /foo?date=2022-02-15

The way I did is location.search = queryString and it works but it results in a full reload. I wanted to use History API from react-router so I can avoid the full reload.

But history.push is going to replace the whole path /foo with date=2022-02-15 (so the URL is going to be date=2022-02-15 as opposed to /foo?date=2022-02-15) as it doesn't append ?date=2022-02-15 to the current path /foo like location.search would do. So is there a way to use history API to achieve the same behavior?

CodePudding user response:

You can get the current pathname from the location object of the current route being matched and rendered.

Example:

const location = useRouteMatch();
const queryString = "date=2022-02-15";

...

// as a string
history.push(`${location.pathname}?${queryString}`);

// or as an object
history.push({
  pathname: location.pathname,
  search: `?${queryString}`,
});
  • Related