Image and ImageBackground
A plant list without photos looks like a spreadsheet. Sprout shows a small photo on every card and a leafy header behind the screen title. Images on a phone have one rule web developers often miss: the app must know how big a remote image is before it arrives.
The rule
Local images use require; remote images need a uri and a size.
There are two kinds of source:
import { Image } from 'react-native';
// Bundled with the app
<Image source={require('./assets/fern.png')} />
// Downloaded from the internet
<Image
source={{ uri: 'https://example.com/photos/fern.jpg' }}
style={{ width: 64, height: 64, borderRadius: 8 }}
resizeMode="cover"
/>- Local images use
requirewith a fixed path. Metro packs the file into the app and knows its size, so it can show it without extra styling. The path must be a literal string;require('./assets/' + name)does not work, because Metro reads requires while bundling. - Remote images use an object with
uri. React Native cannot know their size in advance, so you must setwidthandheightin the style, or the image renders at zero size and is invisible. resizeModedecides how the picture fits its box:'cover'fills and crops,'contain'shows it whole with gaps,'stretch'distorts to fit.altgives screen readers a description.
ImageBackground is an Image that can hold children, for text over a picture:
<ImageBackground
source={require('./assets/leaves.jpg')}
style={{ height: 160, justifyContent: 'flex-end' }}
>
<Text style={{ color: 'white', fontSize: 24 }}>My plants</Text>
</ImageBackground>It also needs a size from its style. Its children sit on top of the image.
The shortcut
For any image, ask "is the file in my project or on the internet?" In the project: require with a fixed path. On the internet: { uri } plus width and height.
Where is the file?
Users take photos, and they are uploaded to a server. On the internet.
Drills
Answer fast — trust the rule.
A remote Image with { uri } and no style shows nothing. Why?
Which is the correct way to show assets/cactus.png from the project?
Which resizeMode shows the whole photo, leaving empty space if the shapes differ?
Why does require('./assets/' + plant.file) fail?
You want the title "My plants" drawn on top of a photo. Which component fits?
Remember
- Local images use
require; remote images need auriand a size. - Ask "in my project or on the internet?"
- Trap: a remote image without
widthandheightis invisible.
