react-rails asset pipeline image path
react-rails asset pipeline image path
I'm using the react-rails gem, and I'm having trouble figuring out how to load images from the asset pipeline.
I handle this currently by using the .js.jsx.erb extension, but as far as I know this is unconventional. (am I correct?)
.js.jsx.erb
Sometimes I just use an empty div and and set the div's background-image property as the image I intend to use.
background-image
What is the best way to go about loading images to react components when using react-rails?
react-rails
1 Answer
1
There are two ways to import image...
1) If you are direct using jsx.erb or js.erb file...
jsx.erb
js.erb
var image_path = "<%= asset_path(my_image.png) %>"
OR
render: function() {
return (
<img src={"<%= asset_url('path/to/image.png') %>"} />
)
}
2) Passing as props Through .erb file to .js.erb or .jsx.erb file
.erb
.js.erb
.jsx.erb
in your .erb file
.erb
render_component('Component', img_src: image_url('the_path'))
in your .js.erb or .jsx.erb file
.js.erb
.jsx.erb
render: function() {
return (
<img src={this.props.img_src} />
)
}
Source: github
jsx.erb
I do know how to get it to work. I want to know what the "best practice" is.
– justcode
Jun 30 at 16:16
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I've tried both ways. Currently I'm doing it the first way, but it seems like most people do not use
jsx.erb. The second way is problematic because sometimes I have to pass the images several levels.– justcode
Jun 30 at 16:16