Taming SVGs in the Wild Wild West of React Native

Romario Fitzgerald
2 min readMay 24, 2023

--

Photo by Мария Волк on Unsplash

Today, we’re exploring a key aspect of image management in React Native — dealing with SVGs or Scalable Vector Graphics. As mobile developers, we often choose SVGs due to their scalable nature, meaning they maintain their quality regardless of size adjustments. Let’s walk through how to integrate SVGs into your React Native project.

1. Incorporating SVGs from Your Assets

Firstly, if you have an SVG in your assets directory that you want to include in your project, you will need to install two necessary libraries: react-native-svg and react-native-svg-transformer.

npm install react-native-svg
npm install --save-dev react-native-svg-transformer

Next, it’s essential to configure Metro (the JavaScript bundler for React Native) to handle SVGs properly. You can achieve this by creating or modifying a metro.config.js file:

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

The last step in setting up is installing your pods on iOS:

cd ios && pod install

With these configurations in place, you can now import SVGs directly in your JavaScript files and use them as React components:

import React from 'react';
import { View } from 'react-native';
import Logo from './assets/logo.svg';
export default function App() {
return (
<View>
<Logo width={120} height={40} />
</View>
);
}

Ensure to replace './assets/logo.svg' with the actual path to your SVG file in the assets directory.

2. Displaying SVGs from a URL

In case your SVG is hosted on a server, React Native still got you covered. You can easily display SVGs from a URL using the SvgUri component from react-native-svg.

Firstly, make sure react-native-svg is installed:

npm install react-native-svg

Then, use SvgUri in your React Native component like this:

import React from 'react';
import { SvgUri } from 'react-native-svg';
export default function App() {
return (
<SvgUri
width="100%"
height="100%"
uri="https://example.com/path-to-your-image.svg"
/>
);
}

Remember to replace "https://example.com/path-to-your-image.svg" with the actual URL of your SVG image.

That’s it for our SVG integration guide. Whether your SVGs are local or hosted online, these techniques should cover all your needs.

--

--

Romario Fitzgerald
Romario Fitzgerald

Written by Romario Fitzgerald

I’m a young software developer and entrepreneur who is always looking for ways to grow.

No responses yet