Home > Software design >  TypeError: Cannot read properties of undefined (reading 'setState')
TypeError: Cannot read properties of undefined (reading 'setState')

Time:10-24

What I am trying?

Trying to set the value of input type text in state

What did I search so far?

enter image description here

Component

import React from 'react';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {email: ""};
    }

    setEmailVal(val) {
        this.setState({email: val.currentTarget.value});
    }

    render() {
        return (
            <input type="text" onChange={this.setEmailVal} value={this.state.email} />
        );
    }    
}

export default Login;

CodePudding user response:

If you declare your function in the following manner

    setEmailVal = val => {
        this.setState({email: val.currentTarget.value});
    }

It works fine.

If you wish to do it in the other (old, if I am not wrong) way, then you'd need to bind the function to the class for the subcomponent, i.e. the onChange handler in the class to "see" it:

    constructor(props) {
        super(props);
        this.state = {email: ""};
        this.setEmailVal = this.setEmailVal.bind(this);
    }

Lastly, you could do a direct bind inside the return component itself

        return (
            <input type="text" onChange={this.setEmailVal.bind(this)} value={this.state.email} />
        );

CodePudding user response:

You can fix this by changing setEmailVal to an arrow function.
Should look like this:

setEmailVal = e => {
   this.setState({email: e.currentTarget.value});
}

Have a look at this for more information on the subject.

  • Related