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 Cannot read properties of undefined (reading, 'setState') on trigger from passed prop

Im working on learning react with a project I thought up.

I have a parent component that has a handleClick function:

handleEmail() {
     console.log('handle email triggered');
    this.setState({
        viewDisabled: 'hide',
        
    })
 }

when I trigger it from within the same component, like

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

<button onClick={this.handleEmail}>handle email</button>

it logs "handle email triggered" and properly sets the state.

I have a child component with a form:

<form onSubmit={this.handleSubmit}>
            <legend>Enter a valid email to start playing!</legend>
      <input type="email" value={this.state.value} onChange={this.handleChange} />

            <input type="submit" value="Submit" onClick={this.props.handleEmail} />
        </form>

called in the parent component like:

  <Email handleEmail={this.handleEmail} onChange={emailHandler} />

When the submit button is clicked, it bubbles up, and the console logs "handle email triggered", but it errors with "Cannot read properties of undefined (reading, ‘setState’)" on attempting to set the same state that the native click can set.
I would think I was doing something wrong, but it follows the same pattern as another child component that works using the same method and I can’t tell the difference.
Any idea what this means would be helpful. I’m guessing it has something to do with state not properly getting set somewhere along the way.
Thanks in advance.

>Solution :

This is an issue with this binding. You can use an arrow function to avoid it. Arrow functions has lexical binding of this.

handleEmail = () => {
     console.log('handle email triggered');
    this.setState({
        viewDisabled: 'hide',
        
    })
 }

Or you can do this binding to the handleEmail inside the constructor of the class component like below.

constructor(props) {
   super(props);
   this.handleEmail = this.handleEmail.bind(this);
}
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