5

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;
Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • 1
    You can try to change `this.setState({email: val.currentTarget.value});` to `this.setState({email: val.target.value});` – tromgy Oct 23 '21 at 10:51
  • 2
    Does this answer your question? [React - uncaught TypeError: Cannot read property 'setState' of undefined](https://stackoverflow.com/questions/32317154/react-uncaught-typeerror-cannot-read-property-setstate-of-undefined) – Mayur Vaghasiya Oct 23 '21 at 11:20

2 Answers2

10

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} />
        );
foreverAnIntern
  • 414
  • 6
  • 15
3

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.

tomleb
  • 2,409
  • 2
  • 9
  • 24