Home > OS >  React Cannot read properties of undefined (reading, 'setState') on trigger from passed pro
React Cannot read properties of undefined (reading, 'setState') on trigger from passed pro

Time:11-20

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

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

CodePudding user response:

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);
}
  • Related