-
-
Notifications
You must be signed in to change notification settings - Fork 32.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[utils] Make getReactElementRef React 19 compatible #44034
[utils] Make getReactElementRef React 19 compatible #44034
Conversation
Netlify deploy previewhttps://deploy-preview-44034--material-ui.netlify.app/ Bundle size reportDetails of bundle changes (Toolpad) |
export default function getReactElementRef( | ||
element: React.ReactElement, | ||
): React.Ref<any> | null | undefined { | ||
export default function getReactElementRef(element: React.ReactElement): React.Ref<any> | null { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The function now returns a ref or null
, no more undefined
. This makes it behave the same in React 18 and React 19. Before this PR, in React 18 it returned undefined
in some scenarios and in React 19 it returned null
for the same scenarios.
// 'ref' is passed as prop in React 19, whereas 'ref' is directly attached to children in older versions | ||
if (parseInt(React.version, 10) >= 19) { | ||
return element.props?.ref; | ||
return (element?.props as any)?.ref || null; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Apart from making it return null
when there's no ref, two other changes in this line:
element.props
is unknown so we need to cast it. With React 19 types, TS reports this error:Property 'ref' does not exist on type '{}'
- Optional chaining added to
element
so it doesn't fail in test cases where the value passed in undefined (getReactElementRef()
)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good, seems like we don't need any other code changes as setRef
already checks for null or undefined, so we are safe.
Extracted from #42824