Overview
Having an appropriately sized image in your app is essential to provide the best viewing experience for your users. React Native requires that dimensions for images are specified, so unlike a website, it's not possible to use srcsets to display images. Instead, you can use two different methods to display your imgix images across different devices optimally.
Showing an Image based on the Dimensions of the Window
Henry at inducesmile.com has a great article on creating responsive images in React Native. You can see a sample of his code with imgix images below:
import React, { Component } from 'react';
import { StyleSheet, Alert, View, Image, Dimensions } from 'react-native';
const { width, height } = Dimensions.get('window');
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Image
source={{ uri: 'http://vuaws.imgix.net/image01.jpg?fit=crop&w=' + width + '&h=' + height }}
style={{ width: width, height: height }}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
});
Modified code snippet from https://inducesmile.com/
With this, you can begin serving responsive images in imgix without having to use any other libraries.
This method integrates the variables for width and height from the dimensions of the device with your imgix API parameters. Simply replace the image with your own, add any other desired parameters, and you will be all set.
You can see the full article from inducesmile.com below:
https://inducesmile.com/react-native-source-code/how-to-create-responsive-image-in-react-native/
Building Image Breakpoints
Author and imgix user Jack Weatherilt also outlines a way to create breakpoints using imgix for React Native without the need to install a library. See his code here:
import React from "react"
import { Image } from "react-native"
const breakpoints = [[100, 100], [200, 200], [300, 300]]
const sources = breakpoints.map([w, h] => ({
uri: `https://assets.imgix.net/unsplash/moon.jpg?fit=crop&w={w}&h={h}`,
height: w,
width: h
})
)
const TheMoon = () => {
return <Image source={sources} />
}
export default TheMoon
Modified code snippet from https://medium.com/finimize-engineering/fetching-responsive-images-in-react-native-to-boost-performance-cd638cd0928e
This method maps image breakpoints to the width and height in order to display images with those breakpoints through React Native.
For the full article by Jack Weatherilt, click this link below:
https://medium.com/finimize-engineering/fetching-responsive-images-in-react-native-to-boost-performance-cd638cd0928e