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"
/>

resizeMode="cover"

Scales the image so that both width and height are equal to or larger than the view dimensions. This option is used by default. React Native Image with `cover` resize-mode

resizeMode="repeat"

Repeats the image to cover the full frame of the view. React Native Image with `repeat` resize-mode

resizeMode="contain"

Scales the image so that both width and height will be equal to or less than the view dimensions. React Native Image with `contain` resize-mode

resizeMode="center"

Centers the image in the view. React Native Image with `center` resize-mode

resizeMode="stretch"

Scales width and height independently (may change the aspect ratio). React Native Image with `stretch` resize-mode

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!