Home > front end >  React TypeError: Cannot read properties of undefined (reading 'name')
React TypeError: Cannot read properties of undefined (reading 'name')

Time:11-02

I am using React with Material UI's Textfield components. Was trying to find out the best way to set the form states with the least redundancy. Like for example, I have 8 different input fields. Instead of having a seperate handler for each input, like for example handleFirstName, handleLastName, handleEmail, handleInfo, etc.

So to accomplish this, I tried to create a handleChange handler which looks like below:

   handleChange = (e) => {
     this.setState({
       [e.target.name]: e.target.value
     });
   }

And on each component,

               <TextField
                className={classes.formInput}
                name="firstName"
                onChange={e => this.handleChange(e.target.value)}
                required
                id=""
                type="text"
                InputLabelProps={{
                  shrink: true,
                }}
                error={!firstName}
                helperText="Name is required"
                label="First Name"
                variant="standard" />
              <TextField
                className={classes.formInput}
                name="lastName"
                onChange={e => this.handleChange(e.target.value)}
                required
                id=""
                type="text"
                InputLabelProps={{
                  shrink: true,
                }}
                label="Last Name"
                variant="standard" />

And here is my state object

 constructor(props) {
    super(props);
    this.state = {
      firstName: '',
      lastName: '',
      ...,
    
    };
  }

These are just two of the input fields, but there are about 6 more fields that look the same. Any idea to combat this undefined name?

CodePudding user response:

The problem is that you are not passing the complete event object. You are passing only the value. That is the reason why you are getting the name as undefined.

Try changing the onChange event to below -

onChange={this.handleChange}

This way you will get the complete event object in the function's e variable.

CodePudding user response:

I think you need to handle multiple input field changes in single function.It is doable. try this

handleChange = (e)=>{
    {name,value} = e.target;
    this.setState({
        [name]=value;
    });
}

finally when to pass the onChange method to fields use :

onChange = {this.handleChange}
  • Related