1

I heard that this is the cool way to define function instead of binding them in constructor:

class Comp extends React.Component {
    delete = id => {

    }

    render() {}
}

but when I try to build I get:

Module build failed: SyntaxError: Unexpected token (7:15)

pointing to equal sign after delete

what I am missing?

3
  • You're probably missing babel (a transpiler that converts newer javascript to older javascript). That syntax isn't in the standard but it exists as a proposal I believe. Commented Nov 13, 2017 at 21:57
  • I have babel. But then I believe question is when it got in specs and is this approved in some escmascript release? I even don't know how to google this. Commented Nov 13, 2017 at 21:59
  • You are missing the npmjs.com/package/babel-plugin-transform-class-properties plugin, create-react-app includes it by default, at least in the actual version Commented Nov 13, 2017 at 22:05

2 Answers 2

2

To define class properties the way you are doing it, you need to activate the experimental babel feature transform-class-properties. This allows you to assign expressions like arrrow functions to class properties:

class Bork {
    //Property initializer syntax
    instanceProperty = "bork";
    boundFunction = () => {
      return this.instanceProperty;
    }

    //Static class properties
    static staticProperty = "babelIsCool";
    static staticFunction = function() {
      return Bork.staticProperty;
    }
  }

Note that this feature is not yet part of the ECMAScript specification and may change in the future.

Sign up to request clarification or add additional context in comments.

1 Comment

Good note that this is not in specs. I kinda expected that.
2

You need an additional babel plugin for this feature:

https://www.npmjs.com/package/babel-plugin-transform-class-properties

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.