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
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.