Skip to content

Commit

Permalink
fix: nativeElement has high priority
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ committed May 17, 2024
1 parent 8057704 commit 723851b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/Dom/findDOMNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ export function isDOM(node: any): node is HTMLElement | SVGElement {
export default function findDOMNode<T = Element | Text>(
node: React.ReactInstance | HTMLElement | SVGElement | { nativeElement: T },
): T {
if (isDOM(node)) {
return (node as unknown) as T;
}

if (node && typeof node === 'object' && isDOM((node as any).nativeElement)) {
return ((node as any).nativeElement as unknown) as T;
}

if (isDOM(node)) {
return (node as unknown) as T;
}

if (node instanceof React.Component) {
return (ReactDOM.findDOMNode(node) as unknown) as T;
}
Expand Down
32 changes: 32 additions & 0 deletions tests/findDOMNode.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { render } from '@testing-library/react';
import * as React from 'react';
import findDOMNode, { isDOM } from '../src/Dom/findDOMNode';
import proxyObject from '../src/proxyObject';

describe('findDOMNode', () => {
it('base work', () => {
Expand Down Expand Up @@ -97,4 +98,35 @@ describe('findDOMNode', () => {

expect(findDOMNode(elementRef.current)).toBe(container.querySelector('p'));
});

it('with proxyObject', () => {
const Demo = React.forwardRef((_, ref) => {
const rootRef = React.useRef<HTMLDivElement>(null);
const spanRef = React.useRef<HTMLParagraphElement>(null);

React.useImperativeHandle(ref, () =>
proxyObject(rootRef.current, {
nativeElement: spanRef.current,
}),
);

return (
<p ref={rootRef} id="root">
<span ref={spanRef} />
</p>
);
});

const holderRef = React.createRef<any>();
const { container } = render(
<React.StrictMode>
<Demo ref={holderRef} />
</React.StrictMode>,
);

expect(holderRef.current.id).toBe('root');
expect(findDOMNode(holderRef.current)).toBe(
container.querySelector('span'),
);
});
});

0 comments on commit 723851b

Please sign in to comment.