Skip to content

Commit

Permalink
[utils] Make getReactElementRef React 19 compatible (#44034)
Browse files Browse the repository at this point in the history
  • Loading branch information
aarongarciah authored Oct 8, 2024
1 parent 48c6682 commit edefd06
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import * as React from 'react';
describe('getReactElementRef', () => {
it('should return undefined when not used correctly', () => {
// @ts-expect-error
expect(getReactElementRef(false)).to.equal(undefined);
expect(getReactElementRef(false)).to.equal(null);
// @ts-expect-error
expect(getReactElementRef()).to.equal(undefined);
expect(getReactElementRef()).to.equal(null);
// @ts-expect-error
expect(getReactElementRef(1)).to.equal(undefined);
expect(getReactElementRef(1)).to.equal(null);

const children = [<div key="1" />, <div key="2" />];
// @ts-expect-error
expect(getReactElementRef(children)).to.equal(undefined);
expect(getReactElementRef(children)).to.equal(null);
});

it('should return the ref of a React element', () => {
Expand Down
10 changes: 4 additions & 6 deletions packages/mui-utils/src/getReactElementRef/getReactElementRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ import * as React from 'react';
* It will throw runtime error if the element is not a valid React element.
*
* @param element React.ReactElement
* @returns React.Ref<any> | null | undefined
* @returns React.Ref<any> | null
*/
export default function getReactElementRef(
element: React.ReactElement,
): React.Ref<any> | null | undefined {
export default function getReactElementRef(element: React.ReactElement): React.Ref<any> | null {
// '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;
}
// @ts-expect-error element.ref is not included in the ReactElement type
// https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/70189
return element?.ref;
return element?.ref || null;
}

0 comments on commit edefd06

Please sign in to comment.