Search code examples
javascriptreactjswebpackecmascript-next

How to use the proposed ECMAscript class syntax with React and Webpack?


I am trying to learn the proposed class syntax for ecmascript and using it with React, i have successfully rendered components with es6 using babel with webpack. Now i want to use instance properties inside classes which are declared outside of the constructor. For eg:

class MyComponent extends React.Component{
  constructor(props){
   super(props)
  }

  property1= "new property"; 
  func1= ()=>{
   }
  }

I am getting the error "unexpected token" on 'property1' and 'func1' while trying to do something like this. also, i am using the babel presets for react and babel-preset-env plugins in webpack.

I want to limit the use of "this" keyword inside my class, so i thought the newer es7 classes could acheive that, how can i do this? any help would be appreciated.

Edit 1: as suggested in the answers, i included the "babel-preset-stage-2" preset , and i was able to include the variables outside of the constructor in the class, but have to use 'this' to reference them.


Solution

  • That syntax isn't "ES7" (by which I assume you mean ES2016, aka the 7th edition). In fact, it's not even ES2017. It's still a Stage 3 proposal. It might make ES2018 if a couple of implementations get done in time for it reach Stage 4 before the cutoff.

    To use it with Babel, enable the stage-3 preset or the specific plugin for that feature (transform-class-properties).