0

We can declare methods of component class as arrow functions, like so:

class SomeComponent extends React.Component {
  someMethod = () => { // <<----- This does not throw error
    // some code
  }
}

..that won't throw any error, but below does:

class SomeNormalClass {
  someMethod = () => { // <<----- This throws error
    // some code
  }
}

It says unexpected = after someMethod. It works fine if I change my someMethod back to normal function instead of declaring it as an arrow function as shown below. Why?

class SomeNormalClass {
  function someMethod() { // <<----- This works fine
    // some code
  }
}
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
  • Related https://stackoverflow.com/questions/31362292/how-to-use-arrow-functions-public-class-fields-as-class-methods – Timo Aug 22 '18 at 12:50
  • 1
    *This works fine* - this is invalid code that will result in syntax error. `function` keyword is out of place. The question lacks https://stackoverflow.com/help/mcve – Estus Flask Aug 22 '18 at 13:30
  • 1
    It has nothing to do with React but with the build tool you are (or are not) using. – Felix Kling Aug 22 '18 at 17:33

2 Answers2

3

Your someMethod in first example is a property of the class, not a method. BabelJS support properties in classes, but native js not. You can see difference here. You should add some properties in constructor for Vanilla JS.

ymd
  • 682
  • 5
  • 18
0

someMethod = () => {...} is class field. Class fields are stage 3 proposal which isn't natively supported and needs to be transformed by transpiler (Babel); someMethod class field is syntactic sugar for constructor code:

constructor() {
  this.someMethod = () => {
    // some code
  }
}

Both SomeComponent and SomeNormalClass are expected to work when used in same conditions. Neither of them will work natively.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565