mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
Also reduce max line width to 100. And remove `lint:types` step for commit sequence, it bothers when committing incomplete (wip) changes.
36 lines
876 B
TypeScript
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);
|
|
});
|
|
}
|