Skip to content

Commit

Permalink
[utils] Bring back getReactNodeRef (mui#44248)
Browse files Browse the repository at this point in the history
  • Loading branch information
aarongarciah authored Oct 29, 2024
1 parent c8bf299 commit 9b9f562
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
24 changes: 24 additions & 0 deletions packages/mui-utils/src/getReactNodeRef/getReactNodeRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as React from 'react';

/**
* Returns the ref of a React node handling differences between React 19 and older versions.
* It will return null if the node is not a valid React element.
*
* @param element React.ReactNode
* @returns React.Ref<any> | null
*
* @deprecated Use getReactElementRef instead
*/
export default function getReactNodeRef(element: React.ReactNode): React.Ref<any> | null {
if (!element || !React.isValidElement(element)) {
return null;
}

// 'ref' is passed as prop in React 19, whereas 'ref' is directly attached to children in older versions
return (element.props as any).propertyIsEnumerable('ref')
? (element.props as any).ref
: // @ts-expect-error element.ref is not included in the ReactElement type
// We cannot check for it, but isValidElement is true at this point
// https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/70189
element.ref;
}
1 change: 1 addition & 0 deletions packages/mui-utils/src/getReactNodeRef/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './getReactNodeRef';
1 change: 1 addition & 0 deletions packages/mui-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,6 @@ export { default as unstable_useSlotProps } from './useSlotProps';
export type { UseSlotPropsParameters, UseSlotPropsResult } from './useSlotProps';
export { default as unstable_resolveComponentProps } from './resolveComponentProps';
export { default as unstable_extractEventHandlers } from './extractEventHandlers';
export { default as unstable_getReactNodeRef } from './getReactNodeRef';
export { default as unstable_getReactElementRef } from './getReactElementRef';
export * from './types';

0 comments on commit 9b9f562

Please sign in to comment.