|
| 1 | +import {useEffect, useState} from 'react' |
| 2 | +import {Image, ImageRequireSource} from 'react-native' |
| 3 | + |
| 4 | +export interface URISource { |
| 5 | + uri: string |
| 6 | +} |
| 7 | +type ImageDimensions = |
| 8 | + | { |
| 9 | + width: number |
| 10 | + height: number |
| 11 | + } |
| 12 | + | undefined |
| 13 | +type FailureCallback = (error: any) => void |
| 14 | + |
| 15 | +/** |
| 16 | + * @param source A local file resource. |
| 17 | + * @returns Original image width and height. |
| 18 | + */ |
| 19 | +function useImageDimensions(source: ImageRequireSource): ImageDimensions |
| 20 | +/** |
| 21 | + * @param source A remote URL |
| 22 | + * @param failure The function that will be called if there was an error, such as failing to retrieve the image (see https://reactnative.dev/docs/image#getsize). |
| 23 | + * @returns Original image width and height. |
| 24 | + */ |
| 25 | +function useImageDimensions( |
| 26 | + source: URISource, |
| 27 | + failure: FailureCallback, |
| 28 | +): ImageDimensions |
| 29 | +function useImageDimensions( |
| 30 | + source: ImageRequireSource | URISource, |
| 31 | + failure: FailureCallback, |
| 32 | +): ImageDimensions |
| 33 | +function useImageDimensions( |
| 34 | + source: ImageRequireSource | URISource, |
| 35 | + failure?: FailureCallback, |
| 36 | +) { |
| 37 | + const [dimensions, setDimensions] = useState<ImageDimensions>() |
| 38 | + useEffect(() => { |
| 39 | + if (typeof source === 'object') { |
| 40 | + if (!failure) { |
| 41 | + throw new Error( |
| 42 | + '"failure" callback parameter is required in case when URI source is using.', |
| 43 | + ) |
| 44 | + } |
| 45 | + const {uri} = source |
| 46 | + Image.getSize( |
| 47 | + uri, |
| 48 | + (width, height) => setDimensions({width, height}), |
| 49 | + failure, |
| 50 | + ) |
| 51 | + } else { |
| 52 | + setDimensions(Image.resolveAssetSource(source)) |
| 53 | + } |
| 54 | + }, [source, failure]) |
| 55 | + return dimensions |
| 56 | +} |
| 57 | + |
| 58 | +export default useImageDimensions |
0 commit comments