2

I'm missing something simple here, I need to access a defined Ref within a useEffect . The debugger shows that this is undefined and therefore I can't do this.refOverlay.current;.

// Ref
const refOverlay = useRef(null); 

// Sample useEffect that references it
useEffect(() => {
    if (props.mode === 'new') {
        let b = this; // Undefined
        let a = this.refOverlay.current; // Error on this line
        if (a) {
            console.log('ok');
        }
    }
}, [props.mode]);

...
return (
{/* JSX Definition */}
        <OverlayTrigger ref={refOverlay} trigger="click" rootClose placement="bottom" overlay={popoverApprover}>
            <a href="javascript:void(0)" className="more-info">TEST</a>
        </OverlayTrigger> 
);
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
gene b.
  • 10,512
  • 21
  • 115
  • 227
  • You don’t need `this`, the variable is in the same scope in arrow functions so you should be able to just use it – Sami Kuhmonen Sep 09 '21 at 16:44
  • Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Emile Bergeron Sep 09 '21 at 17:12

2 Answers2

1

You have defined a functional based component. Which doesn't have the this Simply remove the this keyword and you're fine.

Gandalf The Gray
  • 108
  • 2
  • 10
1

There's no such this in the function component.

  const Title = () => {
    const ref = useRef(null)
    
    useEffect(() => {
      if (ref.current) {
        ref.current.WHATEVERYOUWANTHERE
      }
    }, [])
  }

NOTE: couple of difference between class and function component

  • function component has no this, it's a function
  • function component is only the render function
  • to have state, you need useState
  • to have any persistent storage, you need hook
windmaomao
  • 7,120
  • 2
  • 32
  • 36