react-rails icon indicating copy to clipboard operation
react-rails copied to clipboard

How to get image paths in JSX?

Open jongbeau opened this issue 11 years ago • 32 comments

Is there a way to use rails helpers like asset_path in JSX? If not, what is the best practice for accessing image paths?

jongbeau avatar Mar 16 '15 14:03 jongbeau

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!

ericdfields avatar Mar 16 '15 21:03 ericdfields

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.

ericdfields avatar Mar 16 '15 21:03 ericdfields

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

bowd avatar Mar 16 '15 21:03 bowd

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

ericdfields avatar Mar 16 '15 21:03 ericdfields

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?

jongbeau avatar Mar 16 '15 22:03 jongbeau

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.

bowd avatar Mar 17 '15 06:03 bowd

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.

vipulnsward avatar Mar 17 '15 06:03 vipulnsward

Thanks @ericdfields , I also think if you are using react-rails that its a easiest way to solve this problem.

andyyou avatar Jun 02 '15 05:06 andyyou

@bogdan-dumitru Did you end up writing that blog post? I'd be interested in learning about your experience.

hongkim91 avatar Jul 17 '15 04:07 hongkim91

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.

andyyou avatar Jul 20 '15 00:07 andyyou

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') %>"} />
  )
}

mikesea avatar Aug 13 '15 22:08 mikesea

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

j0214ack avatar Aug 28 '15 01:08 j0214ack

@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') %>" />
    );
  }
}

bcardiff avatar Sep 24 '15 15:09 bcardiff

you guys are awesome ! I was ripping my hair trying to figure this out

arkhamRejek avatar Dec 17 '15 00:12 arkhamRejek

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
);

chalmagean avatar Jan 19 '16 15:01 chalmagean

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>
                &nbsp;
                <%= 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 avatar Feb 01 '16 14:02 pioz

@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 :-)

bcardiff avatar Feb 01 '16 18:02 bcardiff

so if im compiling with webpack, which solution from these posts would work?

gwong89 avatar Feb 12 '16 10:02 gwong89

Store it in a JS variable and use it

varun-raj avatar Mar 01 '16 05:03 varun-raj

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'} />

screen shot 2016-09-11 at 11 35 44 am

tx-ares avatar Sep 11 '16 16:09 tx-ares