I am using React JS. I am setting the state, however, there is a problem, in the value={} part of the input field.
Here is my code:
import React from 'react';
class SomeClass extends React.Component{
constructor(props){
super(props);
this.state = {
passCode: {
email: "Email",
password: "Password"
},
errorMessage: ''
};
}
handleChange = (event) =>{
console.log(`input detected`);
let request = Object.assign({},this.state.passCode);
request.email = event.target.value;
request.password = event.target.value;
this.setState({passCode: request});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>Email Address</label>
<input type="text" value={this.state.passCode.email} onChange={this.handleChange} placeholder="Enter Email Address" />
<label>Password</label>
<input type="password" value={this.state.passCode.password} onChange={this.handleChange} placeholder="Enter One Time Password" />
<Button type="submit">
Sign In</Button>
</form>
);
}
}
export default SomeClass;
My Question:
I have is for the value attribute of the input fields, I think setState is not working properly:
In the passCode object of the state. When I type the email, both fields get set to what I typed in the email field. When I type the password, both fields get set to what I typed in the password field.
What's the reason for such problem?
setState is working properly; your handleChange isn't. You're setting both email and password to the value of the input regardless of which input the change occurred on. Instead, you want to update just the relevant property. To do that, I'd add name attributes to the input elements (name="email" and name="password"), then:
handleChange = ({currentTarget: {name, value}}) =>{
console.log(`input detected`);
this.setState(({passCode}) => {
return {passCode: {...passCode, [name]: value}};
});
};
Key bits there are:
change related to, keeping the other one unchanged, by using the name of the input.setState (best practice since we're setting state based on existing state).Your funtion handleChange is wrong. You should update like this with using name:
handleChange = (event) => {
console.log(`input detected`);
const { name, value } = event.target;
this.setState({ passCode: { ...this.state.passCode, [name]: value } });
};
And set name to input:
<input type="text" value={this.state.passCode.email} onChange={this.handleChange} placeholder="Enter Email Address" name="email" />
<input type="password" value={this.state.passCode.password} onChange={this.handleChange} placeholder="Enter One Time Password" name="password" />
The methods they gaved are good, but I still suggest that you separate the methods of changing the two, maybe it will be much better.