Image in React Native

A deep dive into how to use the Image component in React Native and its modifiers such as resizeMode, alt, defaultSource, and others.

In this tutorial, we'll take a deep dive into how to use the Image component and its modifiers 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 and height 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

React Native Image with cover resize-mode

  • cover (default) - scale the image so that both width and height will be equal to or larger than the view dimensions.

React Native Image with repeat resize-mode

  • repeat - repeat the image to cover the frame of the view.

React Native Image with contain resize-mode

  • contain - scale the image so that both width and height will be equal to or less than the view dimensions.

React Native Image with center resize-mode

  • center - center the image in the view.

React Native Image with stretch resize-mode

  • 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.

Never miss a beat

Stay in the loop with our latest updates and offers - no spam, just the good stuff!