Athos
Athos

Reputation: 43

ReactJS : Error: Maximum update depth exceeded

UPDATE3: I have a navbar created by a .map function of each item. When I click in a navbar item, I want to scroll to a specific div of my SPA, to do that , I created a function to scroll to each ref in each div of my page. My problem is that I need to store those refs to get then in my navbar and when I dynamic create those refs I get this error :

Error: 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.
setMyInputRef2
C:/Users/OMEN/Desktop/Web/tstbst/src/Pages/App.js:62

  60 | 
  61 | setMyInputRef (element) {
> 62 |     this.setState( { main : element });
     | ^  63 | };


 87 |     <div ref={(prop) => {this.setMyInputRef(prop)} }>

where main IS a ref about a div Main

UPDATE4: IT works when I do that:


setMyInputRef = (element) => {
        this.setState( { main : element });
    };

<div ref={this.setMyInputRef} >

But I want to pass args to my function stMyInputRef to indentify each NavbarItem to store the ref, this way I cant pass that arg to my function

That is what I want :


setMyInputRef = (element,stateRef) => {
        this.setState( {"stateRef" : element });
        // stateRef as "div1" 
    };

<div ref={(thisDivRef)=>this.setMyInputRef(thisDivRef,"div1")} >

why I can't do that?

Upvotes: 0

Views: 373

Answers (1)

Miionu
Miionu

Reputation: 52

Your function is called when the ref is calculated, not when the user clicks. This is why you have an infinite loop. When the page loads, the ref calls the function that change the state which then reloads the page , etc...

If you tell us what you are trying to do with this, we could maybe help you to find a solution :)

Upvotes: 1

Related Questions