Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create reverse routes with react-router

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.

like image 738
xanld Avatar asked Feb 24 '17 00:02

xanld


1 Answers

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.

like image 78
skyboyer Avatar answered Sep 25 '22 23:09

skyboyer