File tree Expand file tree Collapse file tree
src/content/reference/react Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -592,3 +592,36 @@ export default MyInput;
592592Then the parent component can get a ref to it.
593593
594594Read 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.
You can’t perform that action at this time.
0 commit comments