c-poulsen c-poulsen - 1 month ago 16
Javascript Question

SyntaxError in component with React.createClass

Im trying to create a function in React which should eventually make some calculations and return the result to my component. The function isn't done, so bear with me if it doesn't make sense where I'm going with this.

I'm using

React.createClass
.

The code looks like this

render: function() {
return (
<div className="container">
<h3 className="time">{this._getTime(1)}</h3>
</div>
);
}

_getTime(time) {
if (time === 1) {
return '1';
} else if (time === 2) {
return '2';
} else {
return 'stuff';
}
}


This just returns a SyntaxError: Unexpected token pointing to the _getTime.
Any hints to what im doing wrong?

Answer

It looks like you're using React.createClass, which accepts an Object argument.

Because it's an Object, you need a comma between each property or shorthand method.

var Hello = React.createClass({
  render: function() {
    return (
      <div className="container">
         <h3 className="time">{this._getTime(1)}</h3>
      </div>
    );
  }, // <--- comma added here

  _getTime(time) {
    if (time === 1) {
      return '1';
    } else if (time === 2) {
      return '2';
    } else {
      return 'stuff';
    }
  }
});

https://jsfiddle.net/pfnfvyb1/

class doesn't use comma delimiters, so this issue is common when switching between the two styles.