Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot run function with useImperativeHandle

I am trying to use useImperativeHandle but still getting error "Cannot add property current, object is not extensible". In every tutorial is code written in similar way and is working correctly. There is something that I am missing, but i dont know what.

Child Element

const Toast = forwardRef((ref) => {
  const [openToast, setOpenToast] = useState(true);

  useImperativeHandle(ref, () => ({
    show() {
      alert("hello");
    },
  }));
  return (
    <div>
    </div>
  );
});

export default Toast;

Parent element

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const FooterForm = () => {
  const toastRef = useRef(null);

  return (
    <>
      <Toast ref={toastRef} />
      <button
        onClick={() => {toastRef.current.show();}}
        type="button">
        Click
        </button>
    </>
  );
};

export default FooterForm;

I need to pass ref to child component and run fuction "show"

>Solution :

ForwardRef components always need exactly to params. The first one is your props, even if they’re empty. Try this:

const Toast = forwardRef((props, ref) => {
  const [openToast, setOpenToast] = useState(true);

In this case, props will just be an empty object, but it will include your component props if you eventually add some.

  • Also, be sure to mark it with the "use client" directive if you haven’t already.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading