Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Custom Ref (Without DOM)

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.

like image 445
Sarmad Shah Avatar asked Nov 02 '25 14:11

Sarmad Shah


1 Answers

Thats when useImperativeHandle used.

useImperativeHandle customizes the instance value that is exposed to parent components when using ref.

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} />;
}

Edit epic-violet-78cc7

like image 67
Dennis Vash Avatar answered Nov 04 '25 06:11

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!