0

I'm a newbie at react.js and was going through some code samples to understand the declarations. However, I came across a scenario where it complains about

getInitialState(): must return an object or null

I cross checked the syntax and everything looked right until I found out that introducing a new line break is causing the issue. Being a front end developer ( spent many years with javascript ) , it doesn't make sense why a simple line break can change the syntax.

Declaration 1 : ( throws error in the console ) https://jsfiddle.net/69z2wepo/68177/

var Test = React.createClass({
    getInitialState : function(){
      return
      {
        counter : 1
      }
    },
    render:function()
    {
      return (
          <div> {this.state.counter} </div>
       );
    }
});

ReactDOM.render(<Test />,
     document.getElementById('container'));

Declaration 2 : ( Works fine ) https://jsfiddle.net/69z2wepo/68178/

var Test = React.createClass({
    getInitialState : function(){
      return { // line break was removed
        counter : 1
      }
    },
    render:function()
    {
      return (
          <div> {this.state.counter} </div>
       );
    }
});

ReactDOM.render(<Test />,
     document.getElementById('container'));

I would appreciate if someone can help me understand this weird behavior.

Lee Brindley
  • 6,242
  • 5
  • 41
  • 62
DinoMyte
  • 8,737
  • 1
  • 19
  • 26
  • See also [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](http://stackoverflow.com/q/2846283/218196) – Felix Kling Jan 23 '17 at 21:59
  • tl;dr: It doesn't have anything to do with React or JSX. – Felix Kling Jan 23 '17 at 22:00
  • @FelixKling: I understand that a line break after the return might change its meaning. However why a line break after the { doesn't justify it. – DinoMyte Jan 23 '17 at 22:02
  • I don't understand. In the first example you start the return value on the next line (therefore the function returns `undefined`). In the second example you start it on the same line (as the `return`). In both cases you have a line break after the first `{`. This is all explained in the two questions I linked to. – Felix Kling Jan 23 '17 at 22:03
  • @FelixKling: Nevermind. I see the point. Thanks for the clarification. – DinoMyte Jan 23 '17 at 22:05

0 Answers0