How to Use SVG in React Native
What is SVG?
Scalable Vector Graphics (SVG) is an XML based language for describing two-dimensional vector graphics. SVG images can be rendered cleanly at any size without loss of quality.
Why do we need SVGs at all?
Yes, it’s clear, the raster images perform poorly and gets pixelated on scaling while vector images don’t. Moreover, the later can do this while maintaining a comparatively low file size.
Unfortunately, rendering SVGs in native is not as simple as it is in HTML/Web, where you can use SVG as an image or copy-paste SVG content inside your HTML. Unlike the web, React Native doesn’t support SVG out of the box. Though some plugins let you render SVG.
react-native-svg
is one such npm package which provides SVG support to React Native on iOS and Android.
Now let’s start by opening terminal and install react-native-svg into your project.
npm install react-native-svg --save
Before the update of React Native 0.60, you need to link the libraries which rely on native code using react-native link
while after the update it does this linking automatically.
But if you run into any linking issue for the above library, do link it.
react-native link react-native-svg
React Native SVG transformer allows you to import SVG files in your React Native project the same way that you would in a Web application when using a library like SVGR to transform your imported SVG images into react components.
Install react-native-svg-transformer to get compile-time and cached transformations of your SVGs into react components.
npm install react-native-svg-transformer --save
Add a file metro.config.js at the root in your project, if not exists, with the code below.
Finally, import your SVG like a regular import to React Native and use it as you would use any other react component.
Also, you can pass height
and width
props to your component to scale them as you need.
That’s all folks! Happy Coding!!
Is this story useful to you? Looking forward to reading your thoughts on how do you use SVGs in your React Native projects.
Further, you’ll see how to use SVGs as react components and customize them using props in React Native projects.