Skip to content

Commit e3db590

Browse files
committed
Add useRef docs for multiple refs on one element
1 parent c7d6b70 commit e3db590

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

src/content/reference/react/useRef.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,3 +592,36 @@ export default MyInput;
592592
Then the parent component can get a ref to it.
593593
594594
Read more about [accessing another component's DOM nodes.](/learn/manipulating-the-dom-with-refs#accessing-another-components-dom-nodes)
595+
596+
### How can I attach more than one ref to a single element? {/*how-can-i-attach-more-than-one-ref-to-a-single-element*/}
597+
598+
Sometimes you need one element to update multiple refs. For example, you might keep a local ref and also receive a ref from a parent.
599+
600+
Use a ref callback that assigns the same DOM node to each ref:
601+
602+
```js
603+
import { useRef } from 'react';
604+
605+
function assignRef(ref, value) {
606+
if (typeof ref === 'function') {
607+
ref(value);
608+
} else if (ref != null) {
609+
ref.current = value;
610+
}
611+
}
612+
613+
function MyInput({ ref: forwardedRef }) {
614+
const localRef = useRef(null);
615+
616+
return (
617+
<input
618+
ref={node => {
619+
assignRef(localRef, node);
620+
assignRef(forwardedRef, node);
621+
}}
622+
/>
623+
);
624+
}
625+
```
626+
627+
This pattern avoids reading `ref.current` during render and works with both object refs and callback refs.

0 commit comments

Comments
 (0)