UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

Why methods as arrow functions work in react classes but not in normal classes?

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
  }
}

Upvotes: 0

Views: 83

Answers (2)

Estus Flask
Estus Flask

Reputation: 222369

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.

Upvotes: 0

ymd
ymd

Reputation: 680

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.

Upvotes: 3

Related Questions