DEV Community

Cover image for How to use SVGs in React Native.
Gautham Vijayan
Gautham Vijayan

Posted on • Updated on

How to use SVGs in React Native.

In this post we will see how you can use SVG images in a react native application.

In React Native, normal images can be rendered without any additional changes, rendering an SVG requires additional configurations.

In your react native application, first install the following packages to use SVG images.

npm i react-native-svg
npm i react-native-svg-transformer
Enter fullscreen mode Exit fullscreen mode

Enter into the android folder -> app folder -> build.gradle and add the following line at the end of the file.

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
Enter fullscreen mode Exit fullscreen mode

Go inside the iOS folder and run pod install.

After installing the packages and implementing the above steps, enter into this metro.config.js file and copy and paste the below code to make sure SVG files are rendered properly.

const {getDefaultConfig} = require('metro-config');

module.exports = (async () => {
  const {
    resolver: {sourceExts, assetExts},
  } = await getDefaultConfig();

  return {
    transformer: {
      babelTransformerPath: require.resolve('react-native-svg-transformer'),
      getTransformOptions: async () => ({
        transform: {
          experimentalImportSupport: false,
          inlineRequires: true,
        },
      }),
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== 'svg'),
      sourceExts: [...sourceExts, 'svg'],
    },
  };
})();

Enter fullscreen mode Exit fullscreen mode

Lets take you have a SVG called logo.svg, what we have to do is we have to import it in your file and use it as a normal tag with height and width as a prop. You can see the code example below.

import {View} from 'react-native';
import React from 'react';
import Logo from './logo.svg';

const App = () => {
  return (
    <View>
      <Logo height={45} width={45} />
    </View>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

You should be able to see your SVG rendered in your screen. This is how you use SVGs in your react native application.

To know more about React & React Native you can checkout my courses in Udemy.

https://www.udemy.com/course/react-native-for-absolute-beginners-with-react-hooks/

Top comments (1)

Collapse
 
delki8 profile image
Ruither Borba

The metro.config.js instructions here might need a fix.