DEV Community

loading...

React Native: Simple responsive Images for all screen sizes with flex.

trackmystories profile image TrackMyStories ・2 min read

Alt Text

Smartphones come in different shapes and sizes, therefore it is paramount our content responds accordingly.

Images can be problematic when delivering our design across different screens. A one size fits all strategy would not work in today's diverse smartphone landscape and would likely result in a user experience nightmare.

The Flexbox module is based on the Cartesian coordinate system, which is distances over two lines running perpendicular, famously known as the
X-axis and Y-axis, with the Cartesian system in mind our container can be calculated with the main axis which runs horizontal, and the cross-axis which runs vertically as illustrated in the image above.

Consider your container as the X-Axis and Y-Axis that holds the Image.

Consider your container as the X-Axis and Y-Axis that holds the Image.

for example:

<View style={styles.container}> // X & Y axis.
<Image /> // value or items`
</View>
Enter fullscreen mode Exit fullscreen mode

The container value has a height and width as per your requirements.

for example:

container : {width: 180, height: 200}
Enter fullscreen mode Exit fullscreen mode

In order to ensure images inside the container adapt to change, we can use percentages to ensure the size is always on par with the height and width of the container.

Therefore, to make the images responsive we can simply set the value of height and width to 100% and resize mode to cover.

<View style={{
    width: 180,
    height: 200,
    aspectRatio: 1 * 1.4,

    }}>
    <Image
    source={{uri : item.image.url}}

    style={{

    resizeMode: ‘cover’,
    width: ‘100%’,
    height: ‘100%’

    }}
    />
</View>
Enter fullscreen mode Exit fullscreen mode

By setting the Image’s height and width to 100% and resize mode to cover, the image will proportionately occupy a 100% of the container's real estate inside of the X and Y-Axis or the container. It will uniformly scale the image whilst maintaining it’s aspect ratio proportionate to the dimensions of the container.

To conclude, the application of geometry can be an effective resource in scalability. The simple notion of a box and the compatibility of its contents is a good way to think about how responsiveness works in our applications. It is important to note that the container’s style has precedence over the image’s style similar to a waterfall effect, that is how the container’s value dictates how high or wide the image can stretch in the UI.

Discussion (2)

pic
Editor guide
Collapse
doutir profile image
Nathan Guedes

I like the Idea but i dont understand why put aspect ratio 1*1.4

Collapse
trackmystories profile image
TrackMyStories Author • Edited

Hey Nathan, the 1*1.4 is just a byproduct of an actual code block and has nothing to do with article. Thank you for pointing that out. :).