0

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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}

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.