Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

ReactJS: Maximum update depth exceeded error

I'm attempting to flip the condition of a part in ReactJS yet I get a error expressing:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside component will update or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

I don't see the infinite loop in my code, would anyone be able to help?

ReactJS segment 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 (
<tr className="Item">
<td>{this.props.config.server}</td>
<td>{this.props.config.verbose}</td>
<td>{this.props.config.type}</td>
<td className={this.state.details ? "visible" : "hidden"}>PLACEHOLDER MORE INFO</td>
{<td><span onClick={this.toggle()}>Details</span></td>}
</tr>
)}
}

export default Item;
by

3 Answers

espadacoder11
that because you 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 at your code

{<td><span onClick={this.toggle()}>Details</span></td>}

you need to make onClick refer to this.toggle not calling it

to fix the issue do this

{<td><span onClick={this.toggle}>Details</span></td>}
sandhya6gczb
You should pass the event object when calling the function :

{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}

If you don't need to handle onClick event you can also type :

{<td><span onClick={(e) => this.toggle()}>Details</span></td>}

Now you can also add your parameters within the function.
RoliMishra
if you don't need to pass arguments to function, just remove () from function like below:

<td><span onClick={this.toggle}>Details</span></td>

but if you want to pass arguments, you should do like below:

<td><span onClick={(e) => this.toggle(e,arg1,arg2)}>Details</span></td>

Login / Signup to Answer the Question.