4

I am using web-packer with react-rails gem to build a online travel app. I am facing a problem of using Rails URL helper in my JSX view with server side rendering:

For example in my jsx view:

#project/app/javascript/packs/app/components/front_end/SearchTripItemComp.erb
<%= link_to "Book Now!", search_trips_path, className: 'btn btn-book' %>

After running I've got this error:

enter image description here

What I can think of, as a work around, is to pass the search_trips_path as props to the Component from my Rails view or use Rails.application.routes.url_helpers directly but this is very inconvenient especially for those jsx views with many links.

I tried to look around web-packer docs but it seems that the gem did not support Rails view helper for erb loader.

Please help advice!

ps: I have erb webpacker loader configured correctly.

channa ly
  • 9,479
  • 14
  • 53
  • 86

1 Answers1

5

Try this in your jsx view:

#project/app/javascript/packs/app/components/front_end/SearchTripItemComp.erb
<%= ActionController::Base.helpers.link_to "Book Now!", Rails.application.routes.url_helpers.search_trips_path, className: 'btn btn-book' %>

Using:

Rails.application.routes.url_helpers.*_path

instead of

*_path

in your .erb files outside views works for url_helpers.

Rails.application.routes.url_helpers.search_trips_path

If you need to generate URLs from your models or some other place, then ActionController::UrlFor is what you're looking for. Read on for an introduction. In general, this module should not be included on its own, as it is usually included by url_helpers (as in Rails.application.routes.url_helpers).

ActionDispatch::Routing::UrlFor

Similarly for link_to you can use:

ActionController::Base.helpers.link_to
Community
  • 1
  • 1
agni10
  • 124
  • 3
  • 11