Skip to content

Instantly share code, notes, and snippets.

@agoiabel
Last active April 1, 2019 06:34
Show Gist options
  • Save agoiabel/c84c3c33fc9f31de0e7e2c394e749fcf to your computer and use it in GitHub Desktop.
Save agoiabel/c84c3c33fc9f31de0e7e2c394e749fcf to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
class FormContainer extends Component {
constructor () {
this.state = {
formControls: {
email: {
value: ''
},
name: {
value: ''
},
password: {
value: ''
}
}
}
}
changeHandler = event => {
const name = event.target.name;
const value = event.target.value;
this.setState({
formControls: {
...this.state.formControls,
[name]: {
...this.state.formControls[name],
value
}
}
});
}
render() {
return (
<form>
<input type="email"
name="email"
value={this.state.formControls.email.value}
onChange={this.changeHandler}
/>
<input type="text"
name="name"
value={this.state.formControls.name.value}
onChange={this.changeHandler}
/>
<input type="password"
name="password"
value={this.state.formControls.password.value}
onChange={this.changeHandler}
/>
</form>
);
}
}
export default FormContainer;
@fones
Copy link

fones commented Mar 27, 2019

This code is not working.

      this.setState({
          formControls: {
            [name]: value
          }
      });

because you have got object inside email, so value will replace whole object.

      this.state = {
          formControls: {
              email: {
                value: ''
              },
   ....

@fones
Copy link

fones commented Mar 27, 2019

You can test here https://codesandbox.io/embed/50n3qwyjzn I have also add fix in comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment