Reputation: 169
I have route in version "react-router-dom": "^6.7.0"
<Route path="/categories" element={<Categories />} />
I am navigating to this "/categories"
route on multiple pages with
onClick={() => {
return navigate("/categories");
}}
Now my concern is that if my route path <Route path="/categories"
changes in future to <Route path="/categories-abcde"
then I will have to change everywhere in program navigate("/categories")
to navigate("/categories-abcde")
.
Is there any name aliasing like <Route path="/categories" element={<Categories />} alias='somename' />
that I can use everywhere in navigate("/somename")
. So that if route path <Route path="/categories"
changed then I do not have to change in navigate("/somename")
everywhere.
Upvotes: 2
Views: 1395
Reputation: 203532
A feature like this doesn't exist in react-router
but doing a global search and replace is a very trivial action. Search and replace can be prone to typos though, either there's a typo on a specific target path so it doesn't get replaced, or the person making the change typo replaces all the target paths.
To resolve this issue the solution is also trivial, store all the route paths in a configuration object.
Example routes.types.js:
export const ROUTES = {
...
CATEGORIES: "/categories",
...
HOME: "/",
...
};
Usage:
<Route path={ROUTES.CATEGORIES} element={<Categories />} />
onClick={() => {
navigate(ROUTES.CATEGORIES);
}}
Now when the route path needs to be updated it is updated in one location where it's declared and all instances of its usage automatically read the updated value.
Upvotes: 2
Reputation: 44275
No, React Router doesn't have an alias
like property.
There are multiple ways to tackle this, eg:
# Define
export const getCategoriesNavigator = () => navigate("/categories");
# Use
onClick={getCategoriesNavigator}
Should your route change, you only have to change a single point
You could extend your route to path="/categories*"
(note the *
)
This way stuff like your example, /categories-abcde
will still be captured by that route, so no need to change any navigate()
Upvotes: 0