debugjavascriptreactCritical
ReactJS: Maximum update depth exceeded error
Viewed 0 times
updateerrormaximumreactjsdepthexceeded
Problem
I am trying to toggle the state of a component in ReactJS but I get an error stating:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
I don't see the infinite loop in my code, can anyone help?
ReactJS component code:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
I don't see the infinite loop in my code, can anyone help?
ReactJS component code:
import React, { Component } from 'react';
import styled from 'styled-components';
class Item extends React.Component {
constructor(props) {
super(props);
this.toggle= this.toggle.bind(this);
this.state = {
details: false
}
}
toggle(){
const currentState = this.state.details;
this.setState({ details: !currentState });
}
render() {
return (
{this.props.config.server}
{this.props.config.verbose}
{this.props.config.type}
PLACEHOLDER MORE INFO
{Details}
)}
}
export default Item;Solution
That is because you are calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on.
This line in your code:
You need to make
To fix the issue do this:
This line in your code:
{Details}You need to make
onClick refer to this.toggle instead of calling it.To fix the issue do this:
{Details}Code Snippets
{<td><span onClick={this.toggle()}>Details</span></td>}{<td><span onClick={this.toggle}>Details</span></td>}Context
Stack Overflow Q#48497358, score: 412
Revisions (0)
No revisions yet.