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:
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.
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
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