react-native-auto-height-image
react-native-auto-height-image copied to clipboard
Support "100%" or flex: 1 width
Is there any update on this?
Did anyone figure out a workaround on this?
Edit, here's what I ended up doing, maybe not the slickest thing ever but it works for me:
const example = () => {
const [wrapperWidth, setWrapperWidth] = useState(0)
return (
<View
style={{ display: 'flex', flexDirection: 'row' }}
onLayout={event => setWrapperWidth(event.nativeEvent.layout.width)}
>
<AutoHeightImage
width={wrapperWidth}
source={{ uri: 'https://i.imgur.com/example.png' }}
/>
</View>
)
}
@coffenbacher good workaround man... it's still a little strange that react-native don't do it for free... I know they say that they don't add this functionality by default when talking of images taken from the web ({{uri:...}} but this decision should be left to the programmer... Sorry for the outburst :)
I enhanced @coffenbacher 's solution a little, so you can also use it also as a ImageBackground.
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<AutoHeightImageProps, "width"> {
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 (
<View
onLayout={onWrapperLayout}
{...containerProps}
style={[
{
alignItems: "center",
display: "flex",
flexDirection: "row",
height: imageHeight,
justifyContent: "center",
width: "100%",
},
containerProps?.style,
]}
>
<AutoHeightImage
onLayout={onImageLayout}
onError={(error) => console.log("error", error)}
width={wrapperWidth}
style={[StyleSheet.absoluteFill]}
{...rest}
/>
{imageHeight ? children : undefined}
</View>
);
};
Usage:
<WrappedAutoHeightImage
source={{
uri:
"https://cdn.pixabay.com/photo/2018/09/24/03/05/cat-3699032_960_720.jpg",
}}
>
<Text>Cats are small lions, prove me wrong</Text>
</WrappedAutoHeightImage>
You can still use this component just as an image, if you don't provide children.