mirror of
https://github.com/idanoo/GoScrobble.git
synced 2024-11-22 16:35:14 +00:00
38 lines
1.1 KiB
JavaScript
38 lines
1.1 KiB
JavaScript
import ownerDocument from 'dom-helpers/ownerDocument';
|
|
import { useState, useEffect } from 'react';
|
|
export var resolveContainerRef = function resolveContainerRef(ref) {
|
|
var _ref;
|
|
|
|
if (typeof document === 'undefined') return null;
|
|
if (ref == null) return ownerDocument().body;
|
|
if (typeof ref === 'function') ref = ref();
|
|
if (ref && 'current' in ref) ref = ref.current;
|
|
if ((_ref = ref) != null && _ref.nodeType) return ref || null;
|
|
return null;
|
|
};
|
|
export default function useWaitForDOMRef(ref, onResolved) {
|
|
var _useState = useState(function () {
|
|
return resolveContainerRef(ref);
|
|
}),
|
|
resolvedRef = _useState[0],
|
|
setRef = _useState[1];
|
|
|
|
if (!resolvedRef) {
|
|
var earlyRef = resolveContainerRef(ref);
|
|
if (earlyRef) setRef(earlyRef);
|
|
}
|
|
|
|
useEffect(function () {
|
|
if (onResolved && resolvedRef) {
|
|
onResolved(resolvedRef);
|
|
}
|
|
}, [onResolved, resolvedRef]);
|
|
useEffect(function () {
|
|
var nextRef = resolveContainerRef(ref);
|
|
|
|
if (nextRef !== resolvedRef) {
|
|
setRef(nextRef);
|
|
}
|
|
}, [ref, resolvedRef]);
|
|
return resolvedRef;
|
|
} |