I'm wondering if there is a recommended way to construct URLs for my links in my react-router
based app. In the world of Zend Framework
for php
, I'd be using a url helper which used reverse routes. I'd feed in my route name and params to a route config, and it would spit out the URL that I'd link to (or push to in the case of react-router
).
I found this: but it looks like it only supports up to version 1 of react-router
. I'm on version 3.
With same intention I've finished up using generatePath
from 'react-router-dom' package.
E.g. projects/routes.js
contains config:
import {generatePath} from "react-router-dom";
export const EDIT = {
route: "/projects/:id",
generate(id) {
return generatePath(this.route, {id})
}
}
And <Route>
relies on .route
part:
<Route path={ProjectRoutes.EDIT.route} component={ProjectEdit} />
While <Link>
relies on .generate()
<Link to={ProjectRoutes.EDIT.generate(someVariable.id)}>Edit me!</Link>
It's definitely not reversing by name. But I found this approach more predictable and flexible since there are no chances to run into name conflict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With