Brian Piercy
Brian Piercy

Reputation: 649

Rails 5.2 + ReactJS: simple rendering issue

I am using Fernando Villalobos' Rails + ReactJS tutorial and have run into a (hopefully) simple rendering issue.

I'm using Rails 5.2.1 and the react-rails gem v2.4.7.

Here is the controller logic:

def index
  @records = Record.all
end

Here is the view:

<%= react_component "Records", { data: @records } %>

Here is the CoffeeScript:

  @Records = React.createClass
    render: ->
      React.DOM.div
        className: 'records'
        React.DOM.h2
          className: 'title'
          'Records'

At this point in the tutorial, the user should see the div, the H2 tag and "Records".

Google Developer's Console confirms React has inserted a <div data-react-class="Records" data-react-props="..."></div> into the HTML - but I don't see any sign of the <h2>Records</h2>. There are no reported errors or warnings. I've tried using equivalent JSX syntax with no change in results. The javascripts/application.js file looks correct too:

//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require react
//= require react_ujs
//= require components
//= require_tree .

What am I missing?

Upvotes: 0

Views: 706

Answers (1)

arminfro
arminfro

Reputation: 1533

Because you have <div data-react-class="Records" data-react-props="..."></div> rendered but not processed you properly miss either the webpacker setup (in case you don't go with sprockets) or just the 'JavaScript pack tag'.

Have you followed the instructions from the 'Get started' section of the react-rails gem? See here

Instructions in short:

Add Gems

Add webpacker and react-rails to your gemfile

Run installers

$ bundle install
$ rails webpacker:install
$ rails webpacker:install:react
$ rails generate react:install

Link the JavaScript pack

add <%= javascript_pack_tag 'application' %> to your view

Generate component

this step may be optional (since you have already written your component)

rails g react:component my_subdirectory/HelloWorld greeting:string

Render it

<%= react_component("HelloWorld", { greeting: "Hello" }) %>

or in your case, as you did <%= react_component "Records", { data: @records } %>

In case it's not working

Try Server side rendering, <%= react_component("Records", { data: @records }, {prerender: true}) %>

Start webpack-dev-server to see what it has to complain about: bin/webpack-dev-server

Upvotes: 2

Related Questions