How to get image paths in JSX?
Is there a way to use rails helpers like asset_path in JSX? If not, what is the best practice for accessing image paths?
Typically you've been able to name your file 'my_script.js.erb' and then call interpolated ruby in your code:
var image_path = "<%= asset_path(my_image.png) %>"
I don't see why my_script.js.jsx.erb wouldn't work!
Might also be #{asset_path(my_image.png)}… that's what it was when I was writing coffee, but I assume that was coffeescript syntax.
This depends a lot on your stack. What @ericdfields mentioned works if you're compiling JSX inside of the rails asset pipeline. If you're using browserify or webpack it's not as straightforward. In the case of browserify what I did for a while is a have a custom preprocessor for the build and a convention to signal that this needs to be processed like:
// ...
render: function() {
return (
<img src="%image_path(some_asset_that_rails_knows.png)%" />
)
}
// ...
This way I would use my custom preprocessor to match /%([a-z]*)_path\((.*)\)%/ and use the proper rails helper with the argument to generate the full asset path and replace that in the build JS.
Nowadays we just use webpack to mange all our frontend assets and it's awesome. Long gone are the days of sprockets :).
@bogdan-dumitru that sort of preprocessing was a blocker at fully converting our stack to webpack. Thanks for sharing. Still basically running a separate webpack process on dev and then having a compilation step for prod via CI or similar? There's still some gaps in the webpack<>sprockets<>rails relationship in my head.
I'm using ES6 and commonJS so I use browserify to do the compiling. Renaming to script.js.jsx.erb was the first thing that I tried and it did not work. Currently, i'm working around this by using a CSS style that sets the content-url. asset_path works fine in the CSS with sprockets.
I have been looking into webpack recently due to the react hot reload feature. How are things working out as a full replacement of sprockets?
It's going really good so for, minus some small snafus due to node instability (because of all the moving parts/dependencies). But it's really interesting. I'm working on a blog post about this so I'll keep you guys posted.
I do what @jongbeau mentioned. Setting a url from style is easier and cleaner. Another way is passing around the values from data attributes, or generated and passed from props. In later case, helpers are freely available when generating props, so it shouldn't be an issue.
Thanks @ericdfields , I also think if you are using react-rails that its a easiest way to solve this problem.
@bogdan-dumitru Did you end up writing that blog post? I'd be interested in learning about your experience.
In fact, it's just a bit trick and not prefect solution, I thought. You can append extension .erb to js(jsx) file and then you can use the ability of erb, but not all of helpers you can use.
If you're just using the asset pipeline, I found a solution.
This does not work:
render: function() {
return (
<img src="<%= asset_url('path/to/image.png') %>" />
)
}
This did work (wrap the src prop in braces):
render: function() {
return (
<img src={"<%= asset_url('path/to/image.png') %>"} />
)
}
Why not
render: function() {
return (
<img src={this.props.img_src} />
)
}
and then in your erb
render_component('Component', img_src: image_url('the_path'))
this way also makes the component more reusable I suppose
@mikesea suggestion works, but since I am using es6 the file needed to be named *.es6.jsx.erb. And the enclosing {...} were not needed.
class MyImage extends React.Component {
render () {
return (
<img src="<%= asset_url('path/to/image.png') %>" />
);
}
}
you guys are awesome ! I was ripping my hair trying to figure this out
Another thing you might prefer is to pass down the asset paths as props, or just use a global object that holds the paths to every asset.
That might look something like this:
# app/controllers/some_controller.rb
def some_action
@images = {
oneIcon: path_to_asset('one_icon.png'),
twoIcon: path_to_asset('two_icon.png')
}
end
private
def path_to_asset(asset)
ApplicationController.helpers.asset_path(asset)
end
# app/views/some_controller/some_action.html.erb
<%= tag :div, data: { images: @images }, id: "root" %>
# app/assets/javascripts/app.js.jsx
var rootElement = document.getElementById("root");
var imagePaths = JSON.parse(rootElement.dataset.images);
window.ReactDOM.render(
<MainComponent imagePaths={imagePaths} />
rootElement
);
In my app/assets/javascripts/components/navbar.js.jsx.erb I can write something like this:
render() {
return(
<div className="navbar-header">
<button className="navbar-toggle collapsed" data-target="#navbar-collapse" data-toggle="collapse" type="button">
<span className="sr-only">
<%= I18n.t('menu.toggle_navigation') %>
</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<ul>
<li>
<%= link_to root_path, className: 'navbar-brand' do %>
<span className='glyphicon glyphicon-home'></span>
<%= I18n.t('menu.now') %>
<% end %>
</li>
<li><%= link_to I18n.t('menu.archive'), archive_path%></li>
</ul>
</div>
);
}
All works fine except for the link_to with block... I have a syntax error: syntax error, unexpected keyword_end, expecting ')'
If I remove the block all works fine.
Any idea?
@pioz not sure, but probably you reach something erb vs rails-erb around http://www.timelessrepo.com/block-helpers-in-rails3 . You may try to use a block with { ... } in the link_to instead of breaking it in multiple <% %>.
But that is just the tip of the iceberg. Rails helpers output html and not jsx-html. So class/className. for/htmlFor, etc attributes need to be translated. And you won't be able to use interpolation with jsx expression attr={...}, since they will be quoted attr="{...}". Knowing that, if those restriction are fine, go for it :-)
so if im compiling with webpack, which solution from these posts would work?
Store it in a JS variable and use it
I am having an issue with the src path... Console reads a bunch of 404 errors for each of the img's. Is there something wrong with my formatting or pathing ?
<img src={'../images/jesseleach.jpg'} />
