8

What I am trying?

Trying to set the value of input type text in state

What did I search so far?

React - uncaught TypeError: Cannot read property 'setState' of undefined

but this does not answer my issue

Error Details

TypeError: Cannot read properties of undefined (reading 'setState')

This error is coming when setting the value of email in the function setEmailVal

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;
2

2 Answers 2

15

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} />
        );
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.