0

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?

3
  • Why does your onClick get changed to ref? Can you share your entire component Commented Jul 13, 2020 at 22:14
  • What is prop, because if this is props, this could be trying to pass the entire props object and its too large? But I'm just spitballing here as it's unclear what you're trying to do exactly Commented Jul 13, 2020 at 22:15
  • Refs are not meant to be stored in state. They are usually used to gain access to the underlying DOM elements so that you can manipulate them outside of the react life-cycle. If you can explain more about what you are trying to do with the Div that might get you a better answer. Also, are you using hooks or classes? Commented Jul 13, 2020 at 22:55

1 Answer 1

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.