Skip to content

Commit d573045

Browse files
authored
feat(utils): add getChildRef (#109)
1 parent 69413ac commit d573045

File tree

3 files changed

+31
-9
lines changed

3 files changed

+31
-9
lines changed

src/useRTGTransitionProps.ts

+2-9
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import {
44
TransitionProps as RTGTransitionProps,
55
TransitionStatus,
66
} from 'react-transition-group/Transition';
7-
import { getReactVersion } from './utils';
7+
import { getChildRef } from './utils';
88

99
export type TransitionProps = RTGTransitionProps & {
1010
children:
@@ -33,15 +33,8 @@ export default function useRTGTransitionProps({
3333
children,
3434
...props
3535
}: TransitionProps) {
36-
const { major } = getReactVersion();
37-
const childRef =
38-
major >= 19 ? (children as any).props.ref : (children as any).ref;
39-
4036
const nodeRef = useRef<HTMLElement>(null);
41-
const mergedRef = useMergedRefs(
42-
nodeRef,
43-
typeof children === 'function' ? null : childRef,
44-
);
37+
const mergedRef = useMergedRefs(nodeRef, getChildRef(children));
4538

4639
const normalize =
4740
(callback?: (node: HTMLElement, param: any) => void) => (param: any) => {

src/utils.ts

+11
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,14 @@ export function getReactVersion() {
1212
patch: +parts[2],
1313
};
1414
}
15+
16+
export function getChildRef(
17+
element?: React.ReactElement | ((...args: any[]) => React.ReactNode) | null,
18+
) {
19+
if (!element || typeof element === 'function') {
20+
return null;
21+
}
22+
const { major } = getReactVersion();
23+
const childRef = major >= 19 ? element.props.ref : (element as any).ref;
24+
return childRef;
25+
}

test/utilsSpec.tsx

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { getChildRef } from '../src/utils';
3+
4+
describe('utils', () => {
5+
describe('getChildRef', () => {
6+
it('should return null if ref is null', () => {
7+
expect(getChildRef(null)).to.equal(null);
8+
});
9+
10+
it('should return null if ref is undefined', () => {
11+
expect(getChildRef(undefined)).to.equal(null);
12+
});
13+
14+
it('should return null if ref is a function', () => {
15+
expect(getChildRef(() => null)).to.equal(null);
16+
});
17+
});
18+
});

0 commit comments

Comments
 (0)