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: getNodeRef #545

Merged
merged 1 commit into from
Jun 6, 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
38 changes: 30 additions & 8 deletions src/ref.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type * as React from 'react';
import { isValidElement } from 'react';
import { isValidElement, version } from 'react';
import { ForwardRef, isFragment, isMemo } from 'react-is';
import useMemo from './hooks/useMemo';

Expand Down Expand Up @@ -64,14 +64,36 @@ interface RefAttributes<T> extends React.Attributes {
ref: React.Ref<T>;
}

function isReactElement(node: React.ReactNode) {
return isValidElement(node) && !isFragment(node);
}

export const supportNodeRef = <T = any>(
node: React.ReactNode,
): node is React.ReactElement & RefAttributes<T> => {
if (!isValidElement(node)) {
return false;
}
if (isFragment(node)) {
return false;
}
return supportRef(node);
return isReactElement(node) && supportRef(node);
};

/**
* In React 19. `ref` is not a property from node.
* But a property from `props.ref`.
* To check if `props.ref` exist or fallback to `ref`.
*/
export const getNodeRef: <T = any>(
node: React.ReactNode,
) => React.Ref<T> | null =
Number(version.split('.')[0]) >= 19
? // >= React 19
node => {
if (isReactElement(node)) {
return (node as any).props.ref;
}
return null;
}
: // < React 19
node => {
if (isReactElement(node)) {
return (node as any).ref;
}
return null;
};
11 changes: 10 additions & 1 deletion tests/ref.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
/* eslint-disable no-eval */
import { fireEvent, render } from '@testing-library/react';
import React, { ReactNode } from 'react';
import type { ReactNode } from 'react';
import React from 'react';
import useEvent from '../src/hooks/useEvent';
import {
composeRef,
getNodeRef,
supportNodeRef,
supportRef,
useComposeRef,
Expand Down Expand Up @@ -199,4 +201,11 @@ describe('ref', () => {
expect(supportNodeRef(refCom) && refCom.ref).toBeTruthy();
});
});

it('getNodeRef', () => {
const ref = React.createRef<HTMLDivElement>();
const node = <div ref={ref} />;

expect(getNodeRef(node)).toBe(ref);
});
});
Loading