Images
Static Image Resources
React Native provides a unified way of managing images and other media assets in your Android and iOS apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:
<Image source={require('./my-icon.png')} />
The image name is resolved the same way JS modules are resolved. In the example above, the bundler will look for my-icon.png in the same folder as the component that requires it.
You can use the @2x and @3x suffixes to provide images for different screen densities. If you have the following file structure:
.
├── button.js
└── img
├── check.png
├── check@2x.png
└── check@3x.png
...and button.js code contains:
<Image source={require('./img/check.png')} />
...the bundler will bundle and serve the image corresponding to device's screen density. For example, check@2x.png, will be used on an iPhone 7, while check@3x.png will be used on an iPhone 7 Plus or a Nexus 5. If there is no image matching the screen density, the closest best option will be selected.
On Windows, you might need to restart the bundler if you add new images to your project.
Here are some benefits that you get:
- Same system on Android and iOS.
- Images live in the same folder as your JavaScript code. Components are self-contained.
- No global namespace, i.e. you don't have to worry about name collisions.
- Only the images that are actually used will be packaged into your app.
- Adding and changing images doesn't require app recompilation, you can refresh the simulator as you normally do.
- The bundler knows the image dimensions, no need to duplicate it in the code.
- Images can be distributed via npm packages.
In order for this to work, the image name in require has to be known statically.
// GOOD
<Image source={require('./my-icon.png')}