UNPKG

2.6 kBJavaScriptView Raw
1import * as React from 'react';
2import * as ReactDOM from 'react-dom';
3import PropTypes from 'prop-types';
4import { exactProp, refType } from '@material-ui/utils';
5import setRef from '../utils/setRef';
6let warnedOnce = false;
7/**
8 * ⚠️⚠️⚠️
9 * If you want the DOM element of a Material-UI component check out
10 * [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element)
11 * first.
12 *
13 * This component uses `findDOMNode` which is deprecated in React.StrictMode.
14 *
15 * Helper component to allow attaching a ref to a
16 * wrapped element to access the underlying DOM element.
17 *
18 * It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801.
19 * For example:
20 * ```jsx
21 * import React from 'react';
22 * import RootRef from '@material-ui/core/RootRef';
23 *
24 * function MyComponent() {
25 * const domRef = React.useRef();
26 *
27 * React.useEffect(() => {
28 * console.log(domRef.current); // DOM node
29 * }, []);
30 *
31 * return (
32 * <RootRef rootRef={domRef}>
33 * <SomeChildComponent />
34 * </RootRef>
35 * );
36 * }
37 * ```
38 *
39 * @deprecated
40 */
41
42class RootRef extends React.Component {
43 componentDidMount() {
44 this.ref = ReactDOM.findDOMNode(this);
45 setRef(this.props.rootRef, this.ref);
46 }
47
48 componentDidUpdate(prevProps) {
49 const ref = ReactDOM.findDOMNode(this);
50
51 if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) {
52 if (prevProps.rootRef !== this.props.rootRef) {
53 setRef(prevProps.rootRef, null);
54 }
55
56 this.ref = ref;
57 setRef(this.props.rootRef, this.ref);
58 }
59 }
60
61 componentWillUnmount() {
62 this.ref = null;
63 setRef(this.props.rootRef, null);
64 }
65
66 render() {
67 if (process.env.NODE_ENV !== 'production') {
68 if (!warnedOnce) {
69 warnedOnce = true;
70 console.warn(['Material-UI: The RootRef component is deprecated.', 'The component relies on the ReactDOM.findDOMNode API which is deprecated in React.StrictMode.', 'Instead, you can get a reference to the underlying DOM node of the components via the `ref` prop.'].join('/n'));
71 }
72 }
73
74 return this.props.children;
75 }
76
77}
78
79process.env.NODE_ENV !== "production" ? RootRef.propTypes = {
80 /**
81 * The wrapped element.
82 */
83 children: PropTypes.element.isRequired,
84
85 /**
86 * A ref that points to the first DOM node of the wrapped element.
87 */
88 rootRef: refType.isRequired
89} : void 0;
90
91if (process.env.NODE_ENV !== 'production') {
92 process.env.NODE_ENV !== "production" ? RootRef.propTypes = exactProp(RootRef.propTypes) : void 0;
93}
94
95export default RootRef;
\No newline at end of file