Have you already experienced heavy apps because of images? We have a solution: you can use SVG as React Native component with react-native-svg and SVGR!
First, what is the main difference between SVG format and PNG format? Let's look at the differences:
To put it in a nutshell:
Here is an example of an SVG icon representing the flag of Japan. We can see the two circles components corresponding to each circles we see on the icon.
There are many ways to use them in your react native app, depending on the kind of picture. If it is a monochromatic icon, you can use Icomoon/Fontello, using the SVG as a font, as explained here: Add custom icons to your React Native application. But since it's a font, we have only one color so it's easily limited. For other icons, I recommend you to use react-native-svg. Let's see a little example.++code class="has-line-data" data-line-start="14" data-line-end="16">++/code>
In our app, we want to use country flag icons. We won't use Icomoon or Fontello because we need multicolor icons. And moreover we use a lot of images (several hundred) with low complexity, so we really should use SVGs. First, let's download the flags here: https://www.flaticon.com/packs/countrys-flags. We can already see that the PNG folder is 10 times bigger than the SVG folder!++code class="has-line-data" data-line-start="14" data-line-end="16">++/code>
Then you have many ways to use these SVGs in your app. For example you can use the component ++code>SvgUri++/code> which loads the SVG and automatically converts it in a component. But I advice you to convert your SVG before, to keep a nice performance on your app. So, you can convert these SVG images to React components thanks to SVGR. To convert all the SVG files from the folder to React components, you just have to run on the command line:
We are using npx, which is an npm tool that makes it easy to use CLI tools and other executables hosted on an npm registry. So no need for any installation! We also add a SVGO config so that SVGO doesn't optimize the SVG to much: react-native-svg doesn't accept a too optimized SVG.
With our example, we get:
Finally, to use them in your app, you need react-native-svg. If you are using Expo, it is already installed. If not, run ++code>yarn add react-native-svg++/code> then link native code with:
And now, you can have all the SVG components you want with your lighter and faster app!