React Native SVG File to Component
When creating a React Native app, you may want to use SVG files as icons. This is a quick guide on how to convert an SVG file to a React Native component.
Use SVG as component
It’s easy to create SVG elements in your RN project by using react-native-svg.
yarn add react-native-svg
| |
Use SVG file
But, it doesn’t support SVG files directly, in order to import a SVG file as a React Component, you will need to use react-native-svg-transformer.
yarn add react-native-svg-transformer
| |
Attribute replacement
Sometime, you may wish change the color (or other attributes) of the SVG element in your code.
By adding this .svgrrc.[js|json] file to your root directory, the react-native-svg-transformer will replace the attribute value with the given props dynamically.
| |
| |
Note: You have to set the
fillto#000in all SVG files, otherwise thereact-native-svg-transformerwill not be able to replace the value.
Change fill color based on the theme
Because I’m using styled-components to style my React app, and I want to the icon’s color follow the theme color, so I implemented the custom template of `svgr.
Modify .svgrrc.[js|json] to use the custom template
| |
By using props.fill || theme.primaryIcon, the fill color will be changed to theme.primaryIcon if the fill prop in the code is not provided, which means I still can override the fill color in the code.
Template
| |