UNPKG

@primer/components

Version:
49 lines (40 loc) 2.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useCombinedRefs = useCombinedRefs; var _react = _interopRequireWildcard(require("react")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * Creates a ref by combining multiple constituent refs. The ref returned by this hook * should be passed as the ref for the element that needs to be shared. This is * particularly useful when you are using `React.forwardRef` in your component but you * also want to be able to access the local element. This is a small anti-pattern, * though, as it breaks encapsulation. * @param refs */ function useCombinedRefs(...refs) { const combinedRef = (0, _react.useRef)(null); _react.default.useLayoutEffect(() => { function setRefs(current = null) { for (const ref of refs) { if (!ref) { return; } if (typeof ref === 'function') { ref(current); } else { ref.current = current; } } } setRefs(combinedRef.current); return () => { // ensure the refs get updated on unmount // eslint-disable-next-line react-hooks/exhaustive-deps setRefs(combinedRef.current); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [...refs, combinedRef.current]); return combinedRef; }