🖼️ Media - Images and Graphics in React Native
The Picture Frame Story
Imagine your phone is like a magical picture frame. This frame can show photos from your camera roll, grab pictures from the internet, or even draw shapes and icons! In React Native, we have special tools to put pictures inside this frame, make them look perfect, and keep them ready for when you need them again.
Let’s explore how to become a master of pictures in your app!
📦 Image Source Types
Where Do Pictures Come From?
Think of images like letters. Letters can come from:
- Your mailbox (local files on your phone)
- A friend far away (from the internet)
- Your own hand (generated as data)
React Native handles all three!
1. Local Images (Static)
These are pictures that live inside your app, like photos in a photo album you carry everywhere.
// Import the image file
import logo from './assets/logo.png';
// Use it in your component
<Image source={logo} />
Why use this? The picture loads super fast because it’s already on the phone!
2. Network Images (From Internet)
These are pictures that live on websites. You need the internet to get them.
<Image
source={{
uri: 'https://example.com/cat.png',
width: 200,
height: 200
}}
/>
⚠️ Important: You MUST tell React Native the width and height for network images!
3. Base64 Images (Data Images)
These are pictures written as secret code text. Useful for tiny icons or when you generate images.
<Image
source={{
uri: 'data:image/png;base64,iVBORw0...'
}}
/>
🔄 Image Loading
The Waiting Game
When you ask for a picture from the internet, it’s like ordering pizza delivery. Sometimes you wait! React Native lets you show something while waiting.
<Image
source={{ uri: 'https://example.com/big-photo.jpg' }}
defaultSource={require('./placeholder.png')}
onLoadStart={() => console.log('Pizza ordered!')}
onLoad={() => console.log('Pizza arrived!')}
onError={() => console.log('Oops, wrong address!')}
/>
Loading States You Can Track
| Event | What It Means |
|---|---|
onLoadStart |
Started loading (pizza ordered) |
onProgress |
Still loading (pizza on the way) |
onLoad |
Finished loading (pizza here!) |
onError |
Something went wrong (pizza lost) |
📐 Image Resize Modes
Making Pictures Fit Perfectly
Imagine putting a big painting into a small frame. What do you do?
React Native gives you 5 choices with resizeMode:
graph TD A["resizeMode Options"] --> B["cover"] A --> C["contain"] A --> D["stretch"] A --> E["repeat"] A --> F["center"] B --> B1["Fills frame, may crop edges"] C --> C1["Shows all, may have gaps"] D --> D1["Squishes to fit exactly"] E --> E1["Repeats like wallpaper"] F --> F1["Centered at original size"]
Examples
// Cover: Picture fills the whole space
<Image
source={myPhoto}
style={{ width: 200, height: 200 }}
resizeMode="cover"
/>
// Contain: See the whole picture
<Image
source={myPhoto}
style={{ width: 200, height: 200 }}
resizeMode="contain"
/>
Quick Guide
| Mode | Best For |
|---|---|
cover |
Profile photos, backgrounds |
contain |
Product images, logos |
stretch |
Decorative patterns |
center |
Icons that shouldn’t resize |
💾 Image Caching
Your Phone’s Memory Box
Caching is like having a memory box. When you see a picture once, your phone keeps a copy so it doesn’t have to download it again!
How to Control Caching
<Image
source={{
uri: 'https://example.com/photo.jpg',
cache: 'force-cache' // Always use saved copy
}}
/>
Cache Options
| Option | What It Does |
|---|---|
default |
Normal caching (smart choice) |
reload |
Always get fresh from internet |
force-cache |
Only use saved copy |
only-if-cached |
Use cache or show nothing |
Pro Tip: Use force-cache for images that never change, like logos!
🚀 Image Prefetching
Getting Ready Before You Need It
Prefetching is like a waiter bringing water before you ask. React Native can download images before you show them!
// Download these images in the background
Image.prefetch('https://example.com/photo1.jpg');
Image.prefetch('https://example.com/photo2.jpg');
// Later, they load instantly!
<Image source={{ uri: 'https://example.com/photo1.jpg' }} />
When to Use Prefetching
- Loading the next page’s images while user reads current page
- Preparing slideshow images ahead of time
- Getting profile pictures before showing a list
// Prefetch multiple images at once
const imagesToLoad = [
'https://example.com/img1.jpg',
'https://example.com/img2.jpg',
'https://example.com/img3.jpg'
];
Promise.all(imagesToLoad.map(url => Image.prefetch(url)))
.then(() => console.log('All images ready!'));
⚠️ Image Error Handling
When Pictures Go Missing
Sometimes pictures break. Maybe the website is down, or the file was deleted. Good apps handle this gracefully!
function MyImage() {
const [hasError, setHasError] = useState(false);
if (hasError) {
return <Text>Picture unavailable</Text>;
}
return (
<Image
source={{ uri: 'https://example.com/maybe-broken.jpg' }}
onError={() => setHasError(true)}
defaultSource={require('./fallback.png')}
/>
);
}
Error Handling Strategies
- Show a fallback image (a placeholder)
- Show a message (like “Image not available”)
- Hide the broken image completely
- Retry loading after a delay
🎨 SVG in React Native
Drawings That Never Get Blurry
SVG stands for Scalable Vector Graphics. Unlike regular photos, SVGs are like instructions for drawing. They stay sharp at ANY size!
Setting Up SVG
First, install the library:
npm install react-native-svg
Using SVG Components
import Svg, { Circle, Rect, Path } from 'react-native-svg';
function MyShape() {
return (
<Svg width="100" height="100">
<Circle
cx="50"
cy="50"
r="40"
fill="blue"
/>
</Svg>
);
}
Loading SVG Files
Use react-native-svg-transformer for SVG files:
import Logo from './assets/logo.svg';
function App() {
return <Logo width={120} height={40} />;
}
Why Use SVG?
| Regular Image | SVG |
|---|---|
| Gets blurry when big | Always sharp |
| Fixed colors | Can change colors with code |
| Larger file size | Usually smaller |
🎯 Vector Icons
Thousands of Icons Ready to Use
Vector Icons are like a treasure chest of tiny pictures. You can change their size and color with code!
Setting Up
npm install react-native-vector-icons
Using Icons
import Icon from 'react-native-vector-icons/FontAwesome';
function MyButton() {
return (
<Icon
name="heart"
size={30}
color="red"
/>
);
}
Popular Icon Sets
| Icon Set | What’s Inside |
|---|---|
| FontAwesome | General icons |
| MaterialIcons | Google’s design icons |
| Ionicons | iOS-style icons |
| Feather | Clean, minimal icons |
Changing Icons Dynamically
function LikeButton() {
const [liked, setLiked] = useState(false);
return (
<Icon
name={liked ? 'heart' : 'heart-o'}
size={30}
color={liked ? 'red' : 'gray'}
onPress={() => setLiked(!liked)}
/>
);
}
🧠 Quick Summary
graph TD A["Images in React Native"] --> B["Sources"] A --> C["Loading"] A --> D["Display"] A --> E["Vectors"] B --> B1["Local files"] B --> B2["Network URLs"] B --> B3["Base64 data"] C --> C1["Caching"] C --> C2["Prefetching"] C --> C3["Error handling"] D --> D1["Resize modes"] E --> E1["SVG graphics"] E --> E2["Vector icons"]
🎉 You Did It!
Now you know how to:
- ✅ Load images from anywhere
- ✅ Make them fit perfectly with resize modes
- ✅ Speed things up with caching and prefetching
- ✅ Handle errors gracefully
- ✅ Use sharp, scalable SVGs and icons
Your apps will look beautiful and load fast. Go build something amazing! 🚀
