In this tutorial, we'll take a deep dive into how to use the Image component and its modifiers in React Native.
- Next post ↑
- TouchableOpacity in React Native
- Previous post ↓
- Text in React Native
Image
Image
component is used for displaying any images in your React Native Application.
It supports various image formats such as JPEG, PNG, GIF, and more.
To display an image, you need to specify the source of the image using the source
prop.
<Image source={require('./path/to/image.png')} />
Web Images
You can also display images from the web by providing a URL as the image source.
Note: You have to manually set
width
andheight
for images loaded over network (it’s 0 by default).
<Image
source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}
style={{width: 200, height: 200}}
/>
Image Resize Mode
The resizeMode
prop allows you to specify how the image should be resized or scaled to fit its container.
<Image
source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}
style={{width: 100, height: 200}}
resizeMode="cover"
/>
Resize Mode Options
cover
(default) - scale the image so that bothwidth
andheight
will be equal to or larger than the view dimensions.
repeat
- repeat the image to cover the frame of the view.
contain
- scale the image so that bothwidth
andheight
will be equal to or less than the view dimensions.
center
- center the image in the view.
stretch
- scale width and height independently (may change the aspect ratio).
Placeholder Image
You can display a placeholder image while the main image is loading using the defaultSource prop.
<Image
source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}
style={{width: 200, height: 200}}
defaultSource={require('./path/to/placeholder.png')}
/>
Error Handling
In case the image fails to load, you can display an alternative image using the onError
prop.
<Image
source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}
defaultSource={require('./path/to/placeholder.png')}
onError={() => console.log('Image failed to load')}
/>
Alternative Text
Make your images accessible to users by providing the alt
description (similar to web).
<Image
source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}
alt="React Native logo"
/>
We hope you enjoyed this content and now better understand how to use Image in React Native.