UNPKG

@primer/components

Version:
47 lines (40 loc) 1.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useCombinedRefs = useCombinedRefs; var _react = require("react"); var _useIsomorphicLayoutEffect = _interopRequireDefault(require("../utils/useIsomorphicLayoutEffect")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * 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); (0, _useIsomorphicLayoutEffect.default)(() => { 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; }