Banner Image

Using SVG’s in React Native.

Dashrath Singh
April 27, 2022
1 Minute Read

scroll

down

Banner Image

Looking for other services or solutions?

ux/ui image
Explore our services

IN A nutshell

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 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

  • Import your .svg file inside a React component:
  • import Logo from ‘./logo.svg’;
  • You can then use your image as a component:
  • <Logo width={120height={40/>

Resources for reference:

https://www.npmjs.com/package/react-native-svg

0 Shares
Tweet
Share
Share
Pin