Lone Learner
Lone Learner

Reputation: 20628

Variable assignment in class scope works in React but not in ES6

This ReactJS code is valid and produces the desired output:

import React from 'react'

class MyComponent extends React.Component {
  state = {'x': 1}

  render() {
    console.log('render: this.state:', this.state)
    return <div>{this.state.x}</div>
  }
}

export default MyComponent

But this very similar ES6 code causes error when running with Node.js:

class MyComponent {
  state = {'x': 1}

  render() {
    console.log('render: this.state:', this.state)
    return <div>{this.state.x}</div>
  }
}

let c = new MyComponent()
c.render()

Here is the error:

$ node foo.js 
/Users/lone/foo.js:2
  state = {'x': 1}
        ^

SyntaxError: Unexpected token =

Why does the second example lead to error when the first example runs fine with ReactJS?

Upvotes: 0

Views: 50

Answers (2)

maazadeeb
maazadeeb

Reputation: 6112

As already mentioned, this is not yet standard and create-react-app has a transpilation babel plugin. But you could make it work by using a flag on Node >= 10.9. The flag is --js-flags="--harmony".

Source

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 84912

That syntax is not yet a standard part of javascript (it's currently a stage 3 proposal). It can be used with the help of babel's class-properties plugin to transpile it into standard javascript. Most likely your react project includes this plugin, which is why it works for you in react. Create-react-app, for example, includes the plugin. Without the plugin, react can't use that syntax either.

Upvotes: 3

Related Questions