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?