Search code examples
javascriptreactjsrefuse-ref

How to pass any anonymous function to ref and use that in other react component?


I have 3 functional components and I'd like to pass & manipulate data through useRef.
I am adding this onClose method to current property in one of my component.

const onClose = () => {
    setButtonColor(buttonColor);
};

ref.current = {
    clearSwitchStateOnClose: onClose,  
};

I am calling that method in another component.

ref.current.clearSwitchStateOnClose();

I am receiving this error,

Uncaught TypeError: ref.current.clearSwitchStateOnClose is not a function

Solution

  • I was calling this method ref.current.clearSwitchStateOnClose(); but with that I was also mutating ref. I guess that was causing the issue.
    It was something like this,

    ref.current = {
        showModal: false,
        modalResponse: null,
    };
    ref.current.clearSwitchStateOnClose();
    

    After doing this, it is working fine.

    ref.current.clearSwitchStateOnClose();
    ref.current = {
        showModal: false,
        modalResponse: null,
    };
    

    Sorry for not sharing the entire scenario of this situation.