How to import SVGs on React Native
On this post, we’ll see which are the options available to use SVGs on our react native project.
Using react-native-svg
According to react-native-svg doc:
react-native-svg
provides SVG support to React Native on iOS and Android, and a compatibility layer for the web.
At first, we were using this library on the project I’m currently working on.
One of the drawbacks of this library is that we can’t use our SVG images directly, we need to create a component through this tool (don’t forget to tick React Native option at the left Global column) and copy the generated component in our project, then we’re able to render it where we need.
Using react-native-svg-transformer
According to react-native-svg-transformer doc:
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.
This makes it possible to use the same code for React Native and Web.
This means we can use our SVG images directly on the project without the need of depending on external tools to generate a compatible component 👏
We just need to save our SVGs on a project folder, then, we import them like this:
import MySVGImage from 'assets/images/svg/my-svg-image.svg';
And we render the imported SVG as a component:
render() {
return(
<MySVGImage />
);
}
You can define the SVGs width and height on the SVG file, the doc suggests to do it on the component, but I think it’s cleaner to do it on the file:
<Logo width={120} height={40} /> //Doc suggestion
Moreover, if you’re using styled components, the SVG can be imported as a styled component so it allows us to apply styles:
When I added this library to the project having previously installed the react-native-svg lib (it is required) I found super easy to make it work and super easy to keep tests related working ok: 0 problems!👌