Skip to content

Commit

Permalink
feat(utils): add getChildRef (#109)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyletsang authored Nov 19, 2024
1 parent 69413ac commit d573045
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 9 deletions.
11 changes: 2 additions & 9 deletions src/useRTGTransitionProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
TransitionProps as RTGTransitionProps,
TransitionStatus,
} from 'react-transition-group/Transition';
import { getReactVersion } from './utils';
import { getChildRef } from './utils';

export type TransitionProps = RTGTransitionProps & {
children:
Expand Down Expand Up @@ -33,15 +33,8 @@ export default function useRTGTransitionProps({
children,
...props
}: TransitionProps) {
const { major } = getReactVersion();
const childRef =
major >= 19 ? (children as any).props.ref : (children as any).ref;

const nodeRef = useRef<HTMLElement>(null);
const mergedRef = useMergedRefs(
nodeRef,
typeof children === 'function' ? null : childRef,
);
const mergedRef = useMergedRefs(nodeRef, getChildRef(children));

const normalize =
(callback?: (node: HTMLElement, param: any) => void) => (param: any) => {
Expand Down
11 changes: 11 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,14 @@ export function getReactVersion() {
patch: +parts[2],
};
}

export function getChildRef(
element?: React.ReactElement | ((...args: any[]) => React.ReactNode) | null,
) {
if (!element || typeof element === 'function') {
return null;
}
const { major } = getReactVersion();
const childRef = major >= 19 ? element.props.ref : (element as any).ref;
return childRef;
}
18 changes: 18 additions & 0 deletions test/utilsSpec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest';
import { getChildRef } from '../src/utils';

describe('utils', () => {
describe('getChildRef', () => {
it('should return null if ref is null', () => {
expect(getChildRef(null)).to.equal(null);
});

it('should return null if ref is undefined', () => {
expect(getChildRef(undefined)).to.equal(null);
});

it('should return null if ref is a function', () => {
expect(getChildRef(() => null)).to.equal(null);
});
});
});

0 comments on commit d573045

Please sign in to comment.