calyxofheld
calyxofheld

Reputation: 2148

integrating jsx and erb in rails app

I read that erb could be used with jsx in a reactjs component, so I figured I'd try using the component to render db objects.

Here's the component:

class Item extends React.Component {
  render () {
    return (
      <% @items.each do |item| %>
        <div class="four wide column">
          <div class="card">
            <%= link_to item do %>
              <div class="item-image">
                <%= image_tag item.image.url(:thumb) %>
              </div>
              <div class="item-info">
                <h1><%= item.title %></h1>
                <span>$<%= item.price %></span>
              </div>
            <% end %>
          </div>
        </div>
      <% end %>
    );
  }
}

Here's the controller:

class PagesController < ApplicationController
    def index
        @items = Item.all
        respond_to do |format|
            format.html
            format.json { render json: @items.to_json}
        end
    end
end

This gives an error "syntax error, unexpected ')'

The jsx renders if I strip out the model loop, object properties, and link_to, but obviously the data that I want to show is missing.

And is this a bad way of doing it? Seems to me like this should be in the views directory - not assets/javascript/components.

Upvotes: 3

Views: 942

Answers (1)

David Bendahan
David Bendahan

Reputation: 4482

If Rails can't render jsx.erb or js.erb files

  1. Go to the webpack configuration file config/webpacker.yml

  2. Manually add the extensions you need; jsx.erb or js.erb...etc

   extensions:
    - .jsx.erb
    - .js.erb
    - .jsx

Never Give Up! 🤘

Upvotes: 2

Related Questions