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.