Question about methods in components

Why this code:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Hello"
    };
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick() {
    this.setState({
      text: "You clicked!"
    });
  }

And not

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Hello"
    };
    this.handleClick = handleClick() { // Is 'this' refering to the constructor?
    this.setState({  // also is 'this' here refering to the constructor?
      text: "You clicked!"
    });
  }
  }
  

Thanks,

Andrej

this is referring to the component MyComponent.

Ok but why not define the handelClick in the constructor??

Because it is a method of the component. The constructor is also a method.

But you are using handelClick to change the state. Why not just put that method in the constructor. What would happen? Compared to putting it outside the constructor and making it a method of class…

You can test it yourself.

How would you call it?

The constuctor is just used to initialize certain properties (in this case state properties) of an instance of the class. You need methods (like handleClick) to perform other actions.

1 Like