React-rails: Link to show page

Created on 10 Nov 2015  路  1Comment  路  Source: reactjs/react-rails

If I'm using react-rails for the index, how do I link to the show page? The link below needs the path.

<a href={this.props.post.id}></a>

Most helpful comment

If it were a Rails template, you might use post_path(post) to generate the link. But since we don't have access to that path from JavaScript, we have to find another solution. The two options I've used are:

  • Pass the route in as a prop, then build the URL, so your example might be:

jsx <a href={this.props.postsPath + "/" + this.props.post.id}></a>

  • Hardcode the URL. Use the /rails/info/routes page to determine what the URL _should_ be, then write it as a string in the JS code. For example:

jsx <a href={"admin/posts/" + this.props.post.id}></a>

I've never tried it, but a third option could be something like JsRoutes, which brings Rails route helpers into JavaScript. If hardcoding is not feasible or too risky, that might be a good solution!

>All comments

If it were a Rails template, you might use post_path(post) to generate the link. But since we don't have access to that path from JavaScript, we have to find another solution. The two options I've used are:

  • Pass the route in as a prop, then build the URL, so your example might be:

jsx <a href={this.props.postsPath + "/" + this.props.post.id}></a>

  • Hardcode the URL. Use the /rails/info/routes page to determine what the URL _should_ be, then write it as a string in the JS code. For example:

jsx <a href={"admin/posts/" + this.props.post.id}></a>

I've never tried it, but a third option could be something like JsRoutes, which brings Rails route helpers into JavaScript. If hardcoding is not feasible or too risky, that might be a good solution!

Was this page helpful?
0 / 5 - 0 ratings