3

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

Sometimes I just use an empty div and and set the div's background-image property as the image I intend to use.

What is the best way to go about loading images to react components when using react-rails?

Novice
  • 575
  • 2
  • 7
  • 16

1 Answers1

3

There are three ways to import image...

1) If you are direct using jsx.erb or js.erb file...

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

in your .erb file

render_component('Component', img_src: image_url('the_path'))

in your .js.erb or .jsx.erb file

render: function() {
 return (
  <img src={this.props.img_src} />
 )
}

3) Recommended: Use .js and .jsx file and render it using view file .html.erb

In view file example.html.erb

<%= react_component("Example", props: {}, prerender: false) %>

In .jsx file Example.jsx

import React, { Component } from "react";
import Image from "<IMAGE_PATH>/image.png";

export default class Example extends Component {
  constructor(props, _railsContext) {
   super(props);
  }

  render(){
    return(
      <div>
       <img src={Image} alt="example" />
      </div>
    )
  }
}

You need to register Example component. In your app > javascript > packs > application.js

import ReactOnRails from "react-on-rails";
import Exmaple from "<COMPONENT_PATH>/Exmaple";

ReactOnRails.register({
 Exmaple
}); 

Source: github

Herat Patel
  • 779
  • 3
  • 10
  • 1
    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. – Novice Jun 30 '18 at 16:16
  • 1
    I do know how to get it to work. I want to know what the "best practice" is. – Novice Jun 30 '18 at 16:16
  • I think 3rd way might help you. I used react-on-rails, you can use react-rails accordingly. – Herat Patel Jul 04 '18 at 14:37
  • It is not specified in the readme but I tried jsx.erb and it works with react-rails@2.6.1 – zenon Dec 28 '20 at 11:35