I have been using React from few years and today I encouraged a very unique use case which I need to tackle. I need to make my own ref. there are certain libraries that do it and I don't yet how they do it.
So basically what I need to do is
const ref = useRef();
/**
where ref.reset(); will work
*/
<Menu ref={ref}/>
My custom component:
const Menu = () => {
const reset = () => {
setValue(0);
}
return <CustomMenuComponent />
}
So basically I need to expose this method in the parent. I know this can be done via state and should be done that way, I have just added a minimum use case for my problem. So basically I need to expose some methods in my component, ideally using refs.
Thats when useImperativeHandle used.
useImperativeHandlecustomizes the instance value that is exposed to parent components when usingref.
const Menu = React.forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
reset: () => {
console.log("reset");
}
}));
return <></>;
});
export default function App() {
const ref = useRef();
useEffect(() => {
ref.current.reset();
}, []);
return <Menu ref={ref} />;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With