React Native SVG Android

2 min readAug 29, 2020

Problem

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

Solution:

You have worked hard on a project which uses SVG. All worked fine until you build a production release on Android. Suddenly all your SVG disappear and you are a bit lost. Here is how would you fix it:

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 the 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 it 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.

--

--

Sameer Jain
Sameer Jain

No responses yet