Reputation: 21
I am doing coursera course on react, and I have problem understanding a piece of code regarding onBlur.
In handleBlur function on removing the (evt) reacts gives error Error: Maximum update depth exceeded.
I am not able to understand why that is required here.
I am new in react.
....
class Contact extends Component {
constructor(props){
super(props);
this.state = {
...
touched : {
firstname : false,
lastname : false,
telnum : false,
email : false
}
};
...
this.handleBlur = this.handleBlur.bind(this);
}
...
handleBlur = (field)=>(evt)=>{
this.setState({
touched:{...this.state.touched, [field]:true}
});
}
...
render()
{
const errors = this.validate(this.state.firstname, this.state.lastname, this.state.telnum, this.state.email)
return(
...
<Form onSubmit={this.handleSubmit}>
<FormGroup row>
<Label htmlFor="firstname" md={2}>First Name</Label>
<Col md={10}>
<Input type="text" id="firstname" name="firstname"
placeholder="First Name"
value={this.state.firstname}
valid = {errors.firstname === ''}
invalid = {errors.firstname !== ''}
onBlur={this.handleBlur('firstname')}
onChange={this.handleInputChange}/>
<FormFeedback>
{errors.firstname}
</FormFeedback>
</Col>
</FormGroup>
...
);
}
}
export default Contact;
Upvotes: 0
Views: 415
Reputation: 160
In your code, onBlur={this.handleBlur('firstname')}
runs immediately and React has an infinity loop on this event. you must wrapping your method with a function.
Use this code:
<Input type="text" id="firstname" name="firstname"
placeholder="First Name"
value={this.state.firstname}
valid = {errors.firstname === ''}
invalid = {errors.firstname !== ''}
onBlur={() => this.handleBlur('firstname')}
onChange={this.handleInputChange}
/>
Upvotes: 1