Skip to content

Commit

Permalink
check for react version instead of using propertyIsEnumerable
Browse files Browse the repository at this point in the history
  • Loading branch information
sai6855 committed Sep 19, 2024
1 parent 0f10b63 commit d05cdaf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,17 @@ import getReactElementRef from '@mui/utils/getReactElementRef';
import * as React from 'react';

describe('getReactElementRef', () => {
it('should throw when not used correctly', () => {
expect(() => {
// @ts-expect-error
getReactElementRef(false);
}).to.throw();

expect(() => {
// @ts-expect-error
getReactElementRef();
}).to.throw();

expect(() => {
// @ts-expect-error
getReactElementRef(1);
}).to.throw();
it('should return undefined when not used correctly', () => {
// @ts-expect-error
expect(getReactElementRef(false)).to.equal(undefined);
// @ts-expect-error
expect(getReactElementRef()).to.equal(undefined);
// @ts-expect-error
expect(getReactElementRef(1)).to.equal(undefined);

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

it('should return the ref of a React element', () => {
Expand Down
14 changes: 8 additions & 6 deletions packages/mui-utils/src/getReactElementRef/getReactElementRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ import * as React from 'react';
* @returns React.Ref<any> | null
*/
export default function getReactElementRef(element: React.ReactElement): React.Ref<any> | null {
const reactMajorVersion = parseInt(React.version.split('.')[0], 10);

// 'ref' is passed as prop in React 19, whereas 'ref' is directly attached to children in older versions
return element.props.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;
if (reactMajorVersion >= 19) {
return element.props?.ref;
}
// @ts-expect-error element.ref is not included in the ReactElement type
// https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/70189
return element?.ref;
}

0 comments on commit d05cdaf

Please sign in to comment.