Using SVG as Component in React Native 0.57

In the previous article, I had tried loading SVG using Plugin method but major drawback was customization in terms of passing props, only the dimension modification was possible.

Image for post
Image for post

Here I am using manual conversion using SVGR Libary which turns a standard SVG into a React Native Compatible Component i.e. JSX format

Step 1: Select the content of your SVG and paste it at the left side workspace at this link and you will see the converted JSX format on the right.

Step 2: Select the React-Native Option at the left most Section of the page, since we use react-native-svg as the base library in React Native.

Step 3: Unselect the SVGO transformation at the left most Section near to the bottom, since selecting this, doesn't give me consistent result for all my SVG’s (My Observation)

Step 4: Copy the resulting code from the right side box and create a file in your React Native Project (Here I am using the default SVG from SVGR Website)

import React from ‘react’
import Svg, { Defs, G, Rect } from ‘react-native-svg’

Step 5: Import the Component and use it as following:

import SvgFile from '../asset/mysvgfile.js'
class MyComponent implements React.Component{

Note: The Component Name in the import should start from a Capital letter and if the same component is used in a complex structure such as objects, then any variable is accepted but in this case, the initial assignment has to be in Capital.

Step 6: The Code in the step 5, will not be able to change the fill color since only height and width props are accepted at the global level of SVG and not fill, which is an internal individual property. So where ever you want to change any property, pass it as a props. Since it is JSX, its the JS realm. So you can do the following:

Wherever you find fill="#231231" which you want to change!
Replace it with fill={props.fill}

then the code specified in step 5 will work perfectly.
This method doesn’t depend on any transformer like babel/Metro thus any react upgrades will not effect the conversion.

Extra: In any case, you have a object mapping and sending the component as props do the following

// First import the Library with rules described above.
// Then assign it to an object as shown below
icon : SvgFile // from step 5

Then if you passing MyObject as props, then you can show the icon as shown below in the next screen.

<this.props.myObject.icon height={23} width={14} fill="#FFFF11" />

Tech Enthusiast, Technopreneur and loves to code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store