React Native SVG Android

Question:

How to display SVG in a react native project for android production release using react-native-svg-uri?

Answer:

react-native-svg-uri have an issue where it doesn’t work when you build a production package. That means none of your SVG will be rendered on the application using this library. However, there is a workaround which I will share here. So let’s take a look at the solution.

We need to create a wrapper component which returns SVG object based on the platform because react-native-svg-uri worked fine on iOS but having an issue with the production release of Android. More details here.

Create a new react-native component. Name it Svg.js and update it with following code

import React from 'react';
import { Platform } from 'react-native'
import SvgUri from 'react-native-svg-uri';
export default({ width, height, source, fill }) => Platform.select({
ios: () => <SvgUri width={width || 24} height={height || 24} source={source} fill={fill} />,
android: () => { const SVG = source; return <SVG width={width || 24} height={height || 24} fill={fill} /> },
})();

This will return SVG based on your platform. So on iOS, it will return SvgUri but on Android, it will return the SVG file itself.

Now let’s create another js file that will work as an image library for the app. Please create a file, imageLibrary.js, and update it with the following code:

import Home from './home.svg';
module.exports = {
Home: Home
}

We are importing our SVG here and then exporting back so it can be available anywhere in our project.

Now we need to install an npm package react-native-svg-transformer and update metro-config.js as below:

const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts }
  } = await getDefaultConfig();
  return {
    transformer: {
      getTransformOptions: async () => ({
        transform: {
          experimentalImportSupport: false,
          inlineRequires: false,
        },
      }),
      babelTransformerPath: require.resolve("react-native-svg-transformer")
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== "svg"),
      sourceExts: [...sourceExts, "svg"]
    }
  };
})();

Finally, use the component like this

import React, { Component } from 'react';
import { View, } from 'react-native';
import SvgUri from './Svg';
import { Home } from './imageManager';
export default () => <View style={{ backgroundColor: '#000000', flex: 1 }}>
<SvgUri fill={'#FF0000'} width={'24'} height={'24'} source={Home} />
</View>

This will show your SVG in android production.

I hope this will help you by sorting out your SVG issue in android production. Please let me know if you have any questions or if you need help with other issues.

Good Luck.