justasking justasking - 9 days ago 6
React JSX Question

Weird class property behaviour

I'm using React and bumped into something weird.

class C extends React.Component {

componentDidMount = this.animate; // <---

animate = () => ...

}


This did not work so I had to change the value of componentDidMount and it worked:

class C extends React.Component {

componentDidMount = () => this.animate(); // Lambda is required?

animate = () => ...

}


Does anyone have a good explanation as to why this is required?

Answer

If you write

class C extends React.Component {
   componentDidMount = this.animate; // <---
   animate = () => ...
}

Then componentDidMount is set to undefined because animate is not set at that time.

With componentDidMount = () => this.animate(); the this.animate(); is resolved every time componentDidMount is called, that's why this does work for you.

If you write it that way:

class C extends React.Component {
   animate = () => ...
   componentDidMount = this.animate; // <---
}

Then componentDidMount will reference the function you assigned to animate before.

Comments