From 715c5596f5f0d805832af7454694289cab3ac987 Mon Sep 17 00:00:00 2001 From: Joe Savona Date: Tue, 9 Apr 2024 11:14:26 -0700 Subject: [PATCH] Fix cloneElement using string ref w no owner --- .../src/__tests__/ReactElementClone-test.js | 23 +++++++++++++++++-- packages/react/src/jsx/ReactJSXElement.js | 2 +- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/react/src/__tests__/ReactElementClone-test.js b/packages/react/src/__tests__/ReactElementClone-test.js index 11bb847518e41..fdf5f26ecc951 100644 --- a/packages/react/src/__tests__/ReactElementClone-test.js +++ b/packages/react/src/__tests__/ReactElementClone-test.js @@ -274,8 +274,22 @@ describe('ReactElementClone', () => { const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => root.render()); - expect(component.childRef).toEqual({current: null}); - expect(component.parentRef.current.xyzRef.current.tagName).toBe('SPAN'); + if (gate(flags => flags.enableRefAsProp && flags.disableStringRefs)) { + expect(component.childRef).toEqual({current: null}); + expect(component.parentRef.current.xyzRef.current.tagName).toBe('SPAN'); + } else if ( + gate(flags => !flags.enableRefAsProp && !flags.disableStringRefs) + ) { + expect(component.childRef).toEqual({current: null}); + expect(component.parentRef.current.xyzRef.current.tagName).toBe('SPAN'); + } else if ( + gate(flags => flags.enableRefAsProp && !flags.disableStringRefs) + ) { + expect(component.childRef).toEqual({current: null}); + expect(component.parentRef.current.xyzRef.current.tagName).toBe('SPAN'); + } else { + // Not going to bother testing every possible combination. + } }); it('should overwrite props', async () => { @@ -371,6 +385,11 @@ describe('ReactElementClone', () => { ) { expect(clone.ref).toBe(element.ref); expect(clone.props).toEqual({foo: 'ef'}); + } else if ( + gate(flags => flags.enableRefAsProp && !flags.disableStringRefs) + ) { + expect(clone.ref).toBe(element.ref); + expect(clone.props).toEqual({foo: 'ef'}); } else { // Not going to bother testing every possible combination. } diff --git a/packages/react/src/jsx/ReactJSXElement.js b/packages/react/src/jsx/ReactJSXElement.js index b429db3326b5e..932ac94078bc2 100644 --- a/packages/react/src/jsx/ReactJSXElement.js +++ b/packages/react/src/jsx/ReactJSXElement.js @@ -869,11 +869,11 @@ export function cloneElement(element, config, children) { if (!enableRefAsProp) { // Silently steal the ref from the parent. ref = config.ref; + owner = ReactSharedInternals.owner; if (!disableStringRefs) { ref = coerceStringRef(ref, owner, element.type); } } - owner = ReactSharedInternals.owner; } if (hasValidKey(config)) { if (__DEV__) {