I'm using react-router v6. I want to navigate to a URL that has searchParams, but I'm not seeing a way to do this out of the box. useNavigate
allows me to navigate to a URL by passing in a string. useSearchParams
allows me to set searchParams on the current page.
I could generate the searchParams using createSearchParams
and then convert it to a string and append it to the end of the URL with a ?
in between, but that seems like a hack.
I'd like to be able to do something like:
const navigate = useNavigate();
// listing?foo=bar
navigate("listing", {
params: {
foo: "bar"
}
});
My hacky workaround:
function useNavigateParams() {
const navigate = useNavigate();
return (url: string, params: Record<string, string | string[]>) => {
const searchParams = createSearchParams(params).toString();
navigate(url + "?" + searchParams);
};
}
const navigateParams = useNavigateParams();
navigateParams("listing", {
foo: "bar"
});
Did I miss something from the documentation?
/:id
isparams.id
, what you're talking about is commonly refered to as thelocation.search
part akaquery-string
. there's a nice helper library that's fairly common for these ops, but I don't think that react-router ships with this stringing / parsing utilites npmjs.com/package/query-string – Burgenlandreact-router-v6
, you might want to update the tag (v4) – Disney