React Native - Images


Advertisements

In this chapter, we will understand how to work with images in React Native.

Adding Image

Let us create a new folder img inside the src folder. We will add our image (myImage.png) inside this folder.

We will show images on the home screen.

App.js

import React from 'react';
import ImagesExample from './ImagesExample.js'

const App = () => {
   return (
      <ImagesExample />
   )
}
export default App

Local image can be accessed using the following syntax.

image_example.js

import React, { Component } from 'react'
import { Image } from 'react-native'

const ImagesExample = () => (
   <Image source = {require('C:/Users/Howcodex/Desktop/NativeReactSample/logo.png')} />
)
export default ImagesExample

Output

React Native Images

Screen Density

React Native offers a way to optimize images for different devices using @2x, @3x suffix. The app will load only the image necessary for particular screen density.

The following will be the names of the image inside the img folder.

my-image@2x.jpg
my-image@3x.jpg

Network Images

When using network images, instead of require, we need the source property. It is recommended to define the width and the height for network images.

App.js

import React from 'react';
import ImagesExample from './image_example.js'

const App = () => {
   return (
      <ImagesExample />
   )
}
export default App

image_example.js

import React, { Component } from 'react'
import { View, Image } from 'react-native'

const ImagesExample = () => (
   <Image source = {{uri:'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'}}
   style = {{ width: 200, height: 200 }}
   />
)
export default ImagesExample

Output

Network Images
Advertisements