Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom method to ref in react

Tags:

reactjs

I have attached a ref to a html component like this:

const myRef = useRef(null);

<button ref={myRef} />

I want to customize myRef, I want to add a util method called myRef.customMethod.

Is it possible to run a function everytime myRef gets set?

like image 205
Noitidart Avatar asked Feb 23 '26 18:02

Noitidart


1 Answers

You could use a callback function for setting the ref:

<button ref={(ref) => {/*access or save ref */}}/>

See React Callback Refs for more info.

As this is currently the only way to manage refs by yourself (and not let React handle them for you), i'm pretty sure this is future safe.

like image 174
NickG Avatar answered Feb 26 '26 09:02

NickG



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!