Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling multiple inputs in React

I am new to React and was learning how to handle multiple inputs in form. Here is the code :

class Login extends Component {

  constructor () {
    super();
    this.state = {
      email: '',
      password: ''
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange (evt) {
    // check it out: we get the evt.target.name (which will be either "email" or "password")
    // and use it to target the key on our `state` object with the same name, using bracket syntax
    this.setState({ [evt.target.name]: evt.target.value });
  }

  render () {
    return (
      <form>

        <label>Email</label>
        <input type="text" name="email" onChange={this.handleChange} />

        <label>Password</label>
        <input type="password" name="password" onChange={this.handleChange} />

      </form>
    );
  }
}

The question is how can this.setState({ [evt.target.name]: evt.target.value }); replace several handlers? Does [evt.target.name] represent both inputs?

like image 686
Dickens Avatar asked Sep 13 '19 13:09

Dickens


1 Answers

[evt.target.name] doesn't necessarily represent both inputs, it merely takes the name of the event's target and makes it the key for setState.

This means that when the email form changes, the this.setState will act as follows:

this.setState({ email: evt.target.value });

For the password this works the same;

this.setState({ password: evt.target.value });

So it doesn't necessarily replace several handlers, it mostly replaces them and supplies a shorter way to handle the event. (Think DNRY (Do Not Repeat Yourself)).

However many fields you have in the form, this.setState({ [evt.target.name]: evt.target.value }); will behave as explained above.

To further elaborate, in your current form, with a field for the email and a field for the password, the following will happen;

handleChange (evt) {
    this.setState({ [evt.target.name]: evt.target.value });
}

Above function will take the event's target and extract the name and value attributes. So for EACH input with this change handler it'll change the function to i.e. the following if the email gets changed;

handleChange (evt) {
    this.setState({ email: "[email protected]" });
}

OR i.e. for the password

handleChange (evt) {
    this.setState({ password: "superstrongpassword" });
}

OR i.e. for the name

handleChange (evt) {
    this.setState({ name: "John Doe" });
}

Hope this helps!

like image 85
Mike Donkers Avatar answered Nov 15 '22 22:11

Mike Donkers