Permalink
Cannot retrieve contributors at this time
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
34 lines (30 sloc)
942 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from 'react'; | |
import useMeasure from 'react-use-measure'; | |
import polyfill from '@juggle/resize-observer'; | |
import mergeRefs from 'typed-merge-refs'; | |
export default function useMaintainRatio<T extends HTMLElement>( | |
ratio: number, | |
options: { active: boolean; change: 'height' | 'width' } = { | |
active: true, | |
change: 'height', | |
}, | |
) { | |
const ref = useRef<HTMLDivElement>(null); | |
const [measureRef, bounds] = useMeasure({ polyfill }); | |
useEffect(() => { | |
if (ref.current && options.active) { | |
if (options.change === 'height') { | |
ref.current.style.height = bounds.width / ratio + 'px'; | |
} else { | |
ref.current.style.width = bounds.height / ratio + 'px'; | |
} | |
} | |
return () => { | |
if (ref.current) { | |
ref.current.style.height = ''; | |
ref.current.style.width = ''; | |
} | |
}; | |
}, [bounds]); | |
return mergeRefs(measureRef, ref) as React.Ref<T>; | |
} |