In my React Native app, I am fetching images from an API with unknown dimensions. How do I auto scale the height if I know my desired width?
Example:
I set t
I built a small component around that problem. It uses react-native-auto-height-image library. The advantage is that you can either use it as a Image or a ImageBackground, if you provide any children.
npm i react-native-auto-height-image
import React, { useState, ReactNode } from "react";
import { ViewProps, View, LayoutChangeEvent, StyleSheet } from "react-native";
import AutoHeightImage, {
AutoHeightImageProps,
} from "react-native-auto-height-image";
interface WrappedAutoHeightImageProps
extends Omit {
children?: ReactNode;
containerProps?: ViewProps;
}
/**
* Uses wrapper to set dynamic width of a AutoHeightImage
* @see https://github.com/vivaxy/react-native-auto-height-image/issues/9
*/
export const WrappedAutoHeightImage = ({
children,
containerProps,
...rest
}: WrappedAutoHeightImageProps) => {
const [wrapperWidth, setWrapperWidth] = useState(0);
const [imageHeight, setImageHeight] = useState(0);
const onWrapperLayout = (event: LayoutChangeEvent) =>
setWrapperWidth(event.nativeEvent.layout.width);
const onImageLayout = (event: LayoutChangeEvent) =>
setImageHeight(event.nativeEvent.layout.height);
return (
console.log("error", error)}
width={wrapperWidth}
style={[StyleSheet.absoluteFill]}
{...rest}
/>
{imageHeight ? children : undefined}
);
};
Usage
// As image
// As image background
This is centered vertically and horizontally per default and has an image as background.
You can pass props to the container via containerProps, all other props are spread to the image. Also feel free to change my provided styles.
Read more about the library here