Daniel Kent
Daniel Kent

Reputation: 63

React-Rails Unexpected Token Error for any function other than render()

I am getting an unexpected token error whenever I add any function before render().

For example:

var App = React.createClass({

  constructor() {
    super();

    this.state = {
      notebooks: {}
    };
  }

  render: function() {
    return (
      <div style={{"height": "100%"}}>
        <NotebookNav notebooks={this.props.notebooks}></NotebookNav>
        <Technique></Technique>      
      </div>
    );
  }
});

This component compiles fine when I delete the constructor() function, but with constructor(), it throws the unexpected token error pointing at render: function(). Anyone have any ideas on how to fix this?

Upvotes: 1

Views: 349

Answers (2)

Komolafe Tolulope
Komolafe Tolulope

Reputation: 591

Yes, this is because you are not separating the function with a comma. You should write it like this

var App = React.createClass({

getInitialState: function() {
  return {
    notebooks: {}
  };
},

render: function() {
  return (
    <div style={{"height": "100%"}}>
      <NotebookNav notebooks={this.props.notebooks}></NotebookNav>
      <Technique></Technique>      
    </div>
  );
 }
});

also should be this.state.notebooks not this.props.notebook

Upvotes: 0

azium
azium

Reputation: 20614

You're confusing syntax here. createClass takes an object as an argument, not an ES6 class. Objects need commas separating items. Also, plain objects don't have a constructor like class does. In React's createClass object spec you probably want getInitialState instead

React.createClass({
  getInitialState() { 
    return { notebooks: {} }
  }, // <--- comma
  render() {...}
})

you could however rewrite the entire thing using an ES6 class (which does not have commas separating methods.

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      notebooks: {}
    };
  } // <--- no comma

  render() {
    return (
      <div style={{"height": "100%"}}>
        <NotebookNav notebooks={this.props.notebooks}></NotebookNav>
        <Technique></Technique>      
      </div>
    );
  }
}

Upvotes: 1

Related Questions