Skip to content

Instantly share code, notes, and snippets.

@pplytas
Created May 22, 2021 10:32
Show Gist options
  • Save pplytas/8adf3c61d4178631062cba821584f847 to your computer and use it in GitHub Desktop.
Save pplytas/8adf3c61d4178631062cba821584f847 to your computer and use it in GitHub Desktop.
import React, { useMemo } from 'react';
import { Image } from 'react-native';
const createMissingDimensionStyle = (source, style) => {
const { width, height } = Image.resolveAssetSource(source);
const aspectRatio = width / height;
if (style.width) return { height: style.width / aspectRatio };
if (style.height) return { width: style.height * aspectRatio };
return {};
};
const ScalableImage = ({ source, style, ...rest }) => {
// Merge array of styles into a single object
if (Array.isArray(style)) style = Object.assign({}, ...style);
// Memoize calculations
const missingDimensionStyle = useMemo(() =>
createMissingDimensionStyle(source, style),
[source, style]
);
return <Image style={[style, missingDimensionStyle]} source={source} {...rest} />;
};
export default ScalableImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment