I'm looking for a way to reliably update a dynamic param in a URL with React Router 5.
My webpage has a global select component that allows to switch between different organizations and the URL can have multiple IDs in it.
The URL may look something like this https://www.baseurl.com/organization/:orgId/site/:siteId/user/:userId
So I need to change the :orgId
param when the select value changes. Does React Router 5
provide a good way to do that (useLocation
and useParams
doesn't seem to have an API for that) or should I manipulate the URL string manually in such case?
CodePudding user response:
You may be able to use the useParams
hook and combine it with the generatePath
utility function.
Example:
import { generatePath, useParams } from 'react-router-dom';
...
const params = useParams(); // { orgId, siteId, userId }
...
const path = generatePath(
"/organization/:orgId/site/:siteId/user/:userId",
{
...params, // <-- shallow copy in the existing param values
orgId: newOrgId, // <-- override the specific param values from state/etc
},
);
Use the computed path
variable in history.replace
or as a Link
component target.
CodePudding user response:
useNavigate
provides a way to somehow do it but I think you have to create a function that manually handles the URL params.
// import useNavigate
import {useNavigate} from 'react-router-dom';
export default function App() {
const navigate = useNavigate();
const handleClick = () => {
// navigate programmatically
navigate({pathname: '/about', search: '?query=abc&page=25'});
};
return (
<div>
<button onClick={handleClick}>Navigate to About</button>
</div>
);
}