-
Notifications
You must be signed in to change notification settings - Fork 186
/
findDOMNode.ts
41 lines (34 loc) · 1.07 KB
/
findDOMNode.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import React from 'react';
import ReactDOM from 'react-dom';
export function isDOM(node: any): node is HTMLElement | SVGElement {
// https://developer.mozilla.org/en-US/docs/Web/API/Element
// Since XULElement is also subclass of Element, we only need HTMLElement and SVGElement
return node instanceof HTMLElement || node instanceof SVGElement;
}
/**
* Retrieves a DOM node via a ref, and does not invoke `findDOMNode`.
*/
export function getDOM(node: any): HTMLElement | SVGElement | null {
if (node && typeof node === 'object' && isDOM(node.nativeElement)) {
return node.nativeElement;
}
if (isDOM(node)) {
return node as any;
}
return null;
}
/**
* Return if a node is a DOM node. Else will return by `findDOMNode`
*/
export default function findDOMNode<T = Element | Text>(
node: React.ReactInstance | HTMLElement | SVGElement | { nativeElement: T },
): T {
const domNode = getDOM(node);
if (domNode) {
return domNode as T;
}
if (node instanceof React.Component) {
return ReactDOM.findDOMNode?.(node) as unknown as T;
}
return null;
}