5

I'm using the react-rails gem and I'm trying to write a few components in ES6 that look like this.

My link_list.js.jsx file

import Component from 'react';
import Links from 'link';

class LinkList extends React.component{
  constructor(props){
    super(props);
    this.sate = {};
  }

  getInitialState(){
    return { links: this.props.initialLinks}
  }


  render(){
    var links = this.state.links.map(function(link){
      return <Links key={link.id} link={link} />
    })

    return (
      <div className="links">
        {links}
      </div>
    )
  } 
}

I keep getting this Uncaught ReferenceError: require is not defined and an error that says Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).

and the error Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

Is this a problem with my code or is it a problem with the gem not compiling ES6 right?

Dillon Cortez
  • 186
  • 1
  • 3
  • 17

2 Answers2

2

There's an option in the generate command

rails generate react:component Label label:string --es6

https://github.com/reactjs/react-rails#options

Otherwise, you could use webpack to setup the frontend and use babel.

Edmund Lee
  • 2,514
  • 20
  • 29
0

Normally React code must be "compiled", usually with Babel.

Since this is not a "RoR" concern, I would recommend keep Rails and React separated, adding extra JS layers inside RoR is confusing, harder to debug and unnecessary.

You must generate a bundle.js file with webpack and call it from your rails layout, this way RoR and React don't pollute each other. First install the packages you need with npm like:

 $ npm i react --save
 $ npm i babel-preset-es2015 --save

then compile the bundle.js

webpack -d --display-reasons --display-chunks --progress

My current webpack file :

https://github.com/aarkerio/vet4pet/blob/master/webpack.config.js

use the option "webpack -w" so when you make changes in your .jsx files, bundle.js is automatically updated.

You will need activate source-maps on your browser to debug your code.

aarkerio
  • 2,183
  • 2
  • 20
  • 34
  • as javascript is part of your web application, I have a different opinion and say this is a RoR concern. What about asset fingerprinting? Why is wanting to include CoffeeScript, Sass compilation into RoR any different to wanting to include React in the asset compilation process? I'm not saying it's easy - what I am saying is that I would rather my React app live inside of Rails - I see it as part of the website ecosystem, and as such would prefer solutions to keeping it that way. – Louis Sayers Nov 27 '16 at 23:36