How to use SVG files in your react native application?
If you are reading this article, you probably know what SVG already is. Nevertheless, it doesn’t harm to quickly define what is SVG.
SVG stands for Scalable Vector Graphics. This file format allows us to display vector images on web/mobile applications. However, the question is, why is it a big deal? And why should you use it instead of a pixilated image? It’s very simple, you can scale up and down SVG images without losing any quality.
Let’s get started then and create a react native project with expo:
expo init svg-tutorial-rn
Choose the blank bare workflow. Open your project in your favorite editor.
Now you are ready to add your first SVG image. To do that, first, install the following library
npm i — save react-native-svg
This library allows you to use SVGs in your app, with support for interactivity and animation. (ref. Expo Svg documentation https://docs.expo.io/versions/latest/sdk/svg/)
Now we need to be able to transform the SVG file into React components. Therefore, we need to install another library that handles this transformation for us.
npm i — save react-native-svg-transformer
Once our installation is done, we need to add and adjust some configuration files.
First of all, create (if it doesn’t already exist) the following config file: metro.config.js and paste the following code inside:
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"]
}
};
})();
Go to app.json file add the following:
"expo": {
"packagerOpts": {
"config": "metro.config.js",
"sourceExts": [
"expo.ts",
"expo.tsx",
"expo.js",
"expo.jsx",
"ts",
"tsx",
"js",
"jsx",
"json",
"wasm",
"svg"
]
}
}
You are all set up! You are ready to render your SVG images!
Here is a very cool website where you can find many aesthetic SVG images: https://stories.freepik.com/
Download the one that appealed to you the most, rename it to reactSvg.svg, and place under your assets folder.
Now you can import that SVG file anywhere in your app using:
import ReactSvg from “your_path/reactSvg.svg”
And you can use it as a component as follows:
<ReactSvg />
You can also adjust the width and the height using the width and height properties as follows:
<ReactSvg width={100} height={40}/>
(Tip: restart your expo project after you edit your configuration files)
I hope this was helpful. In case you have any question, please don’t hesitate to ask me.