3

I'm trying to get the react-rails gem (version 2.1) working in my Rails 4.2.4 app. I've gone through the setup steps in the Readme and I'm using webpacker for the js preprocessing. I have a component inside of app/javascript/components/label.js that looks like this:

import React, {PureComponent} from 'react';
import ReactDOM from 'react-dom'

export default class Label extends PureComponent {

  render () {
    return (
      <div>Something rendered in React</div>
    )
  }
}

And then I reference this in my view with the following line:

= react_component("Label")

As far as I can see from the Readme, this should be all that is necessary in order to render the component (provided the application pack is included in the layout, which it is)

= javascript_pack_tag 'application'

So I'm confused as to why I'm getting the error in my browser that the component is not defined.

Uncaught ReferenceError: Label is not defined

Opening app/javascript/packs/application.js I can see the following:

console.log('Hello World from Webpacker')
// Support component names relative to this directory:
var componentRequireContext = require.context("components", true)
var ReactRailsUJS = require("react_ujs")
ReactRailsUJS.useContext(componentRequireContext)

First I verified that the console log is displayed in the browser (it is). I'm not sure what componentRequireContext does, but if it is relative to the current file, then it seems odd that it points to components and not ../components, but changing this doesn't render the component. However, I can get the component rendering if I add the following line:

window.Label = require('../components/label.js');

I thought the React Rails gem took care of this though, provided the components were saved in the app/javascript/components directory? There's nothing in the Readme that says that I need to explicitly declare and require the component, or am I mistaken?

purpletonic
  • 1,858
  • 2
  • 18
  • 29

1 Answers1

2

It looks like you have a capitalization issue. You named the file 'label.js' but you are looking for '= react_component("Label")' So it looks and doesn't find what Label is. Then when you set Label on the window then react is like "Oh ok, Label is actually label.js." and it does stuff. TLDR capitalization matters.

ruby_newbie
  • 3,190
  • 3
  • 18
  • 29
  • 1
    Also, to add to this, make sure that you only have 1 extension. I was using `Label.js.jsx` and is running into the same problem. Renaming it to `Label.jsx` worked. – Rystraum May 03 '17 at 06:07