Using SVG’s in React Native.
React native by default doesn’t support svg we have to use PNG to use graphics in the apps. But we can use react-native-svg package to enable using svg in react native.
react-native-svg provides SVG support to React Native on iOS and Android, and a compatibility layer for the web.
- Installation yarn add react-native-svg
- Now you can use svg from URL directly
import * as React from 'react'; import { SvgUri } from 'react-native-svg'; export default () => ( <SvgUri width="100%" height="100%" uri="http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg" /> );
- But to use svg files go through the following steps
- Install yarn add –dev react-native-svg-transformer
- Modified metro.config.js like this
metro.config.js:
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"] } }; })();
My monorepo metro.config.js using with mono Repo tools. Dont forget write () at the end of the function to make it self executing.
- For type script users make file: declarations.d.ts like this
- More info in react svg Transformer is here: https://github.com/kristerkari/react-native-svg-transformer#installation-and-configuration
- Import your .svg file inside a React component:
- import Logo from ‘./logo.svg’;
- You can then use your image as a component:
- <Logo width={120} height={40} />
Resources for reference: