react-use/src/useEnsuredForwardedRef.ts
xobotyi b6993a6f95
feat(prettier): make prettier a part of eslint.
Also reduce max line width to 100. And remove `lint:types` step for
commit sequence, it bothers when committing incomplete (wip) changes.
2021-02-01 18:58:55 +03:00

36 lines
876 B
TypeScript

import {
forwardRef,
ForwardRefExoticComponent,
MutableRefObject,
PropsWithChildren,
PropsWithoutRef,
RefAttributes,
RefForwardingComponent,
useEffect,
useRef,
} from 'react';
export default function useEnsuredForwardedRef<T>(
forwardedRef: MutableRefObject<T>
): MutableRefObject<T> {
const ensuredRef = useRef(forwardedRef && forwardedRef.current);
useEffect(() => {
if (!forwardedRef) {
return;
}
forwardedRef.current = ensuredRef.current;
}, [forwardedRef]);
return ensuredRef;
}
export function ensuredForwardRef<T, P = {}>(
Component: RefForwardingComponent<T, P>
): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>> {
return forwardRef((props: PropsWithChildren<P>, ref) => {
const ensuredRef = useEnsuredForwardedRef(ref as MutableRefObject<T>);
return Component(props, ensuredRef);
});
}