Reputation: 3705
I'm trying to familiarise myself with react router 6. Not a fan of it so far. I think this dynamic relative/absolute thing just makes it more complicated and vulnerable.
I'm upgrading from v5, and I was able to replace params without explicitly knowing the current path like:
const LinkReplaceItemId = ({ itemId }) => {
const { path } = useRouteMatch();
const params = useParams();
return (
<Link to={generatePath(path, { ...params, itemId })}>Link</Link>
)
}
There was no need to specify a pattern for the route match, it just matched whatever the current path is, and replaced the required params.
Now I have to specify the pattern to get the current path. What if I don't know the pattern - the component can be child of different route structures?
Consider the case where this can be used in:
Just made up some examples to show an example where I want to keep the current url, just want to replace a specific piece.
How to do that in react router 6?
Upvotes: 3
Views: 4881
Reputation: 202836
You can achieve this but it would require using an externally declared array of route path patterns that can be matched. Use the matchPath
utility to iterate the array of patterns and compare against the current location.pathname
value. Once you have the correct path pattern you can generate the new path and override the path params.
Example:
import {
useLocation,
useParams,
generatePath,
Link,
matchPath
} from "react-router-dom";
const routes = [
"/items/:itemId",
"/users/:userId/items/:itemId",
"/collections/:itemId/properties"
];
const LinkReplaceItemId = ({ itemId }) => {
const { pathname } = useLocation();
const pathPattern = routes.find((pattern) => matchPath(pattern, pathname));
const params = useParams();
return <Link to={generatePath(pathPattern, { ...params, itemId })}>Link</Link>;
};
Upvotes: 2