Images and SVGs
Should we use images or SVGs? Should we be putting them in the React Native bundle, or on native and save OTA bandwidth? Let's look at the best practices.
One important decision while building a React Native app is whether you should put an image in a React Native bundle and serve it over-the-air (OTA), i.e. with the React Native bundle, or put it in native and save bundle size. The answer depends on the use case, and we'll look at some pointers that can help us come to that decision.
SVGs#
SVG or Scalable Vector Graphics is an Extensible Markup Language-based vector image format for two-dimensional graphics with support for interactivity and animation.
SVGs play an important part in getting that pixel-perfect rendering on any device resolution. In React Native, SVGs help with a lot more than just rendering icons, and can help render micro-animations too. We'll see how to do that in the Bonus Lottie section.
Be careful though; SVGs are XMLs and can require a lot of computation, so in complex cases, they may render well on high-end devices but have performance issues on low spec ones, especially Android devices. Remember to test on the devices of your user base before pushing to them.
SVGs are not natively supported by React Native. We will be using the library react-native-svg
for the same. Details of its implementations are covered in the Bonus Content's React Native SVG section. For now, we can safely assume that these will be used as simple React components.
// Declaration - assets/svgs/index.ts
import Svg, { Path, G, Circle } from 'react-native-svg';
const HomeActive = ({ style, color }) => (
<Svg viewBox="0 0 1190 1000" style={style}>
<Path
fill={color}
d="M1148 609L952 414v562c0 15-9 24-23 24H262c-14 0-24-9-24-24V414L43 609c-10 10-24 10-33 0s-10-23 0-33L576 9c5-9 10-9 19-9 5 0 15 0 19 5l572 571c9 10 9 24 0 33-15 10-29 10-38 0z"
/>
</Svg>
);
// Usage - someComponent.tsx
import SVGIcons from '../../icons/svgs/index';
.
.
<SVGIcons.HomeActive style={{ width: 12, height: 12 }} />
Images#
As discussed in the Icons and Badges lesson, images in apps are generally uploaded in three versions, demo_image.png
, [email protected]
and [email protected]
(or other supported formats such as .jpg). This is done to support higher dpi devices. If you add only the @3x
version image, the application will be able to resize that for 1x
and 2x
device needs, so, I recommend adding only the 3x
resolution image. So, I recommend adding only the 3x resolution image - you don't need to include that in the file name though.
To upload a
home.png
image of resolution 22 x 20, instead of uploading three versions e.g.,22 x 20
,44 x 40
and66 x 60
, just upload a single imagehome.png
with size66 x 60
.
This page is a preview of The newline Guide to React Native for JavaScript Developers using TypeScript