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.

src/components/home/Home.js

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

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

Local image can be accessed using the following syntax.

src/components/home/ImagesExample.js

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

const Home = () ⇒ (
   <Image source = {require('../../img/myImage.png')} />
)
export default Home
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.

src/components/home/Home.js

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

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

It will show the following output −

React Native Network Image

Advertisements
E-Books Store