Skip to content
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

feat(utils): add getChildRef #109

Merged
merged 1 commit into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
});
});
Loading