How to set image width to be 100% and height to be auto in react native?
Solution 1:
So after thinking for a while I was able to achieve height: auto in react-native image. You need to know the dimensions of your image for this hack to work. Just open your image in any image viewer and you will get the dimensions of the your image in file information. For reference the size of image I used is 541 x 362
First import Dimensions from react-native
import { Dimensions } from 'react-native';
then you have to get the dimensions of the window
const win = Dimensions.get('window');
Now calculate ratio as
const ratio = win.width/541; //541 is actual image width
now the add style to your image as
imageStyle: {
width: win.width,
height: 362 * ratio, //362 is actual height of image
}
Solution 2:
"resizeMode"
isn't style property. Should move to Image component's Props
like below code.
const win = Dimensions.get('window');
const styles = StyleSheet.create({
image: {
flex: 1,
alignSelf: 'stretch',
width: win.width,
height: win.height,
}
});
...
<Image
style={styles.image}
resizeMode={'contain'} /* <= changed */
source={require('../../../images/collection-imag2.png')} />
...
Image's height won't become automatically because Image component is required both width and height in style props
. So you can calculate by using getSize() method for remote images like this answer and you can also calculate image ratio for static images like this answer.
There are a lot of useful open source libraries -
- react-native-auto-height-image
- react-native-fullwidth-image
- react-native-fit-image