Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  51] [ 2]  / answers: 1 / hits: 42623  / 5 Years ago, fri, september 13, 2019, 12:00:00

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?


More From » reactjs

 Answers
30

[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!


[#51659] Thursday, September 5, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;