Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React: How to read state from within handler function?

I’m new to React working on an existing React component (that appears to be built in an older style – no hooks).

I want to read and set state within a handler function. I have the following code:

export default class MyComponent extends React.Component { 

static defaultProps = {
    data: {}
};

constructor(props) {
     super(props);

     // Other states

     this.state.myState = false;
};

handleMyChange() {
    if (!this.state.myState) {
        console.log("hello world");
    }
}

However I get the error Cannot read properties of undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried various like state.myState but am not really sure what I should be doing.

Can anyone point me in the right direction?

>Solution :

In order to have this context in your function, you will need to bind it in the constructor first

Here is a small example is taken from the official doc:

import React from "react";

export default class SayHello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: "Hello!" };
    // This line is important!
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    alert(this.state.message);
  }

  render() {
    // Because `this.handleClick` is bound, we can use it as an event handler.
    return <button onClick={this.handleClick}>Say hello</button>;
  }
}

Edit withered-snow-z17lju

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading