How to import SVG files in React Native using react-native-svg - LogRocket Blog (2024)

Editor’s note: This article was last updated by Joseph Mawa on 1 March 2024 to include information about implementing React Native SVG animation using the react-native-animation package, rendering animated SVGs using React Native WebView, how to simplify importing SVG files in your RN project, and more.

How to import SVG files in React Native using react-native-svg - LogRocket Blog (1)

When you’re developing a React Native application, you may need to implement icons. The easy way to do this is to simply extract the .png or .jpeg file of the icon and use it in the Image component of React Native. This would do the trick for you, but you wont get crisp quality and you’ll end up bloating your app with higher image file sizes, which will increase your app bundle size.

Instead of using .png or .jpeg files in your React Native app, you should be using the SVG format. SVG is a vector-based format that can scale infinitely without compromising quality.

In this guide, you’ll learn how to implement SVG icons in your React Native app using the react-native-svg library.

What are Scalable Vector Graphics (SVG)?

SVG is an XML-based format used to render vector images. A vector image can scale however much you want without pixelating because they use mathematical equations and do not have pixels like other image formats, such as .png and .jpeg.

Because of the vector nature of the SVG format, the image is independent of resolution. An SVG image looks sharp on any screen, from the gorgeous 285 DPI pixel density screens found on new smartphones to the 85 DPI screens of standard monitors. SVG files are also small in size compared to other image formats.

If you open an SVG file in a text editor, you’ll see a large XML code with numbers and various nodes. In this tutorial, we won’t focus on the SVG itself. Instead, we’ll demonstrate rendering SVGs on a mobile app screen.

Does React Native support SVGs?

Rendering SVGs in mobile apps is not as simple as on the web, where you can use SVG directly as an image source or paste the SVG code into your HTML file. This is because there isn’t a built-in React Native component that can render SVGs directly.

Because React Native doesn’t provide default support for SVGs, we’ll have to install a few libraries from the npm package registry. Luckily, there’s a popular npm package called react-native-svg that works well for most use cases.

Let’s start by setting up a React Native project. Run the following command:

npx react-native init SvgDemoApp

To install the react-native-svg and react-native-svg-transformer packages, navigate into the project directory and run the following commands:

cd SvgDemoAppnpm i react-native-svgnpm i --save-dev react-native-svg-transformer

react-native-svg provides SVG support to your React Native project on both Android and iOS platforms. react-native-svg-transformer enables you to import local SVG files in your React Native project, like how you would do in a Creact React App project on the web.

If you’re using the Expo CLI instead of React Native CLI, you can start by running the following commands:

expo init SvgDemoAppexpo install react-native-svg

Rendering SVG shapes in React Native

Let’s look at how you can use the react-native-svg library to render SVGs in your app.

Open the project directory in your favorite text editor and start by importing the Svg and Circle components from react-native-svg, as shown below:

import Svg, { Circle } from 'react-native-svg';

The <Svg> component is a parent component needed to render any SVG shape. It’s like a container component for all your SVG shapes. If you’re rendering any SVG shape, such as a circle or a polygon, you must use this as a wrapper around your SVG component:

<Svg height="50%" width="50%" viewBox="0 0 100 100" > ...</Svg>

The <Svg> component takes three props: height, width, and viewBox. The viewBox prop describes how to position your SVG in space. The height and width props are self-explanatory.

Inside the <Svg> component, render the <Circle> component as follows:

<Svg height="50%" width="50%" viewBox="0 0 100 100" > <Circle cx="50" cy="50" r="50" stroke="purple" strokeWidth=".5" fill="violet" /></Svg>

The <Circle> component takes the x and y coordinates as cx and cy props, respectively. These coordinates define how and where your SVG component will be positioned inside the container. If you were to render a different SVG shape, such as a rectangle, the same would be represented by x and y props, respectively.

To describe the radius of the circle, you can pass an integer as a string to the r prop. You can set this value to increase or decrease the size of the rendered SVG circle.

The stroke prop can be used to denote the color of the border around the SVG element and the strokeWidth represents the thickness of that border. Finally, the fill prop indicates the color of the rendered SVG element. These props are similar to the attributes on the native HTML <svg> element and are common across most of the SVG components.

Over 200k developers use LogRocket to create better digital experiencesLearn more →

Have a look at the entire code that renders an SVG circle on the screen:

import React from 'react';import { StyleSheet, View } from 'react-native';import Svg, { Circle } from 'react-native-svg';export default function App() { return ( <View style={styles.container}> <Svg height="50%" width="50%" viewBox="0 0 100 100" > <Circle cx="50" cy="50" r="50" stroke="purple" strokeWidth=".5" fill="violet" /> </Svg> </View> );}const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', },});

You should see a violet SVG circle, as shown below:

How to import SVG files in React Native using react-native-svg - LogRocket Blog (4)

Notice that I’ve wrapped the <Svg> component inside a <View> component. You can wrap your SVG components inside any generic container component, such as <View> or any other custom wrapper component. This allows you to place and position your SVG components anywhere on the screen using flexbox layouts, as in the above example.

Similarly, you can render other SVG shapes, such as rectangles, polygons, lines, ellipses, etc. However, you need to be aware that react-native-svg doesn’t support all SVG elements yet.

You can compose the supported SVG elements, like in the above example, only when creating basic SVG shapes. In real-world applications, you can use online tools such as SVGR.

Copy and paste the SVG code into the online SVGR playground. It will transform the SVG into a React component that you can use with react-native-svg.

How to render SVG images and icons loaded from a URI in React Native

Now that you understand how to create and render SVGs using the react-native-svg library, let’s explore how you can render SVG icons and images loaded from a URI.

Here, you need to use a different component called SvgUri, so let’s import it from the library:

import { SvgUri } from 'react-native-svg';

The <SvgUri> component takes the width, height, and uri props. You can specify the uri prop pointing to the SVG’s URL. For instance, if you wish to render this SVG, you can assign that URL to the uri prop in your <SvgUri> component, as shown below:

<SvgUri width="100%" height="100%" uri="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/debian.svg"/>

This is quite similar to rendering images in React, where you’d specify the src attribute of your <img> as the URL of the image.

The above code should render the SVG on the screen as shown below:

How to import SVG files in React Native using react-native-svg - LogRocket Blog (5)

You can adjust the width and height of the SVG using the width and height props of the <SvgUri> component. Unlike when rendering SVG shapes, you don’t need a container component here.

Using react-native-svg-transformer

In the previous sections, we explored using react-native-svg to create and render SVGs in a React Native application. However, in some cases, you may need to reference a local SVG icon or an image inside your project.

When setting up the example project, recall that you also installed react-native-svg-transformer as a development dependency. You can use it to render a local SVG icon or image inside your project.

More great articles from LogRocket:

  • Don't miss a moment with The Replay, a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

With react-native-svg-transformer, you can import raw SVG assets as React components. It transforms the SVGs into a format that is compatible with react-native-svg out of the box.

Make configurational changes to your project before using react-native-svg-transformer. Head over to your project’s metro.config.js file. If this file doesn’t exist in your project, create it.

Then, add the following code inside it:

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'], }, };})();

Next, download an SVG and save it inside your project, similar to how you’d download an image that you want to use in your project. Let’s say you named your SVG file image.svg. You can now import this SVG file like any other React component:

import SVGImg from './image.svg';

And render it inside any component:

<SVGImg width={200} height={200} />

The above code should render the same SVG on the screen. If your project requires you to render SVG icons locally, you can follow this approach to render different SVG icons in your app.

Rendering SVGs using XML strings

In rare cases, if you’re not able to reference local SVGs using react-native-svg-transformer, you can use XML strings to render SVGs in a React Native app.

Let’s say you’ve downloaded another example SVG to your project. If you view the SVG file in a text editor like VS Code, you’ll notice the XML code with an <svg> HTML element. You can directly render an SVG from its XML code using the <SvgXml />component:

import { SvgXml } from 'react-native-svg';

Copy everything inside the <svg> element from the SVG file’s XML code and store it inside a string variable.

const xml = `<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">...</svg>`;

Then, pass the above variable to the xml prop inside your <SvgXml> component, as shown below:

<SvgXml xml={xml} width="100%" height="100%" />

And voila! You should now see the following SVG on the screen:

How to import SVG files in React Native using react-native-svg - LogRocket Blog (6)

Implementing React Native SVG animation

One of the benefits of using SVG is that you can animate them using JavaScript and CSS. However, React Native doesn’t have built-in high-performance SVG animation capabilities. Therefore, implementing SVG animations may not be trivial.

In this section, we will explore some techniques you can use to add dynamic and interactive graphics in React Native using SVGs.

Using React Native Reanimated

React Native’s built-in animation API is low-level. Therefore, using it for animating SVGs without third-party packages may be difficult.

In this section, we will use React Native Reanimated to animate the violet circle we created using react-native-svg in one of the sections above. We have already installed react-native-svg. You can install React Native Reanimated from the npm package registry using one of the commands below:

# npmnpm install react-native-reanimated# yarnyarn add react-native-reanimated# exponpx expo install react-native-reanimated

After successfully installing React Native Reanimated, add the react-native-reanimated/plugin plugin to your project’s babel.config.js like so:

module.exports = { presets: [ ... // don't add it here ], plugins: [ ... // it needs to be the last in the list 'react-native-reanimated/plugin' ]};

After adding the above babel plugin, it’s recommended that you reset the Metro bundler cache using one of the following commands:

# npmnpm start -- --reset-cache# yarnyarn start --reset-cache# exponpx expo start -c

If you’re developing for Android, that’s everything you need to start using React Native Reanimated. However, if you’re developing for iOS, also install pods:

cd ios && pod install 

Let’s animate the violet circle we created above. We will create a pulse effect by animating its radius and opacity. Create a component file, and copy and paste the code below:

import React, {useEffect} from 'react';import Svg, {Circle} from 'react-native-svg';import Animated, { useSharedValue, useAnimatedProps, withRepeat, withTiming, Easing,} from 'react-native-reanimated';const AnimatedSVGCircle = Animated.createAnimatedComponent(Circle);function AnimatedPulseCircle() { const pulse = useSharedValue(0); const style = useAnimatedProps(() => { return { r: 10 + pulse.value * 35, opacity: 1 - pulse.value, }; }); useEffect(() => { pulse.value = withRepeat( withTiming(1, {duration: 800, easing: Easing.linear}), -1, false, ); }, [pulse]); return ( <Svg width={100} height={100}> <AnimatedSVGCircle cx={50} cy={50} r={50} stroke="purple" strokeWidth=".5" fill="violet" animatedProps={style} /> </Svg> );}export default AnimatedPulseCircle;

In the code above, we used createAnimatedComponent to wrap the Circle element from react-native-svg. To animate props or styles associated with a component, you wrap it in createAnimatedComponent as in the example above.

The useSharedValue Hook is one of the built-in hooks in React Native Reanimated. It’s for defining shared values in a component. It returns an object with a single value property. You can directly access and modify the value property. In the above example, we are setting its value to the animation object returned by the withRepeat animation modifier in the useEffect Hook.

In React Native Reanimated, an animation modifier is a higher-order function you can use to customize animations. React Native Reanimated has several built-in animation modifiers. One of them is withRepeat. As its name suggests, withRepeat is for repeating an animation many times. In the above example, we are repeating the animation indefinitely.

The useAnimatedProps Hook creates an animated props object. It’s for animating properties of third-party components. In the above example, we passed the returned object to the <AnimatedSVGCircle /> component as the value of animatedProps.

You will get the animation below if you render the component above:

How to import SVG files in React Native using react-native-svg - LogRocket Blog (7)

Using React Native WebView

Another way you can render animated SVGs in React Native is by using React Native WebView. You need to first install React Native WebView from the npm package registry like so:

npm install react-native-webview

You can use SVGator’s online tool to create an SVG animation and embed it in your React Native project using React Native WebView. The online tool has a feature for exporting your animated SVG for React Native out of the box.

After generating your SVG animation, copy and paste the code into your React Native project and render the generated component. Review the SVGator documentation to learn how to use it to create SVG animations.

I exported one of the example SVG animations in SVGator. The GIF below shows what it looks like after rendering the generated component:

How to import SVG files in React Native using react-native-svg - LogRocket Blog (8)

Conclusion

SVGs are great for rendering images and icons you want to use in your React Native apps. You can even use them to create complex shapes and patterns to add more aesthetic appeal to your app’s design.

Remember that storing a large number of SVG files locally will still bloat your app. You should always avoid saving a large number of SVG files in your project and referencing them locally. If you absolutely need to, you can optimize your SVG files using this SVG Optimizer.

I hope this tutorial makes it easier to use SVGs in your React Native project. You can also explore and play around with examples illustrated in the react-native-svg official docs.

LogRocket: Instantly recreate issues in your React Native apps

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your React Native apps — try LogRocket for free.

How to import SVG files in React Native using react-native-svg - LogRocket Blog (2024)

FAQs

How do I pass SVG in react-native? ›

By default, React Native doesn't support importing SVG files directly. Instead, it requires SVG files to be converted to React Native components before they can be used. react-native-svg-transformer simplifies this process by automatically transforming SVG files into React Native components during the build process.

How to use a local SVG image in react? ›

We can use inline SVG directly in React components by including the SVG code as a distinct <svg> element. It involves embedding the SVG markup directly within the JSX code of a React component. In this example, we directly embed a sample SVG element into the App component.

What is react-native SVG? ›

react-native-svg provides SVG support to React Native on iOS, Android, macOS, Windows, and a compatibility layer for the web.

How to use custom SVG icons in react-native? ›

Here are the steps to achieve this:
  1. Get an SVG file. If you are working with Figma, right-click on the SVG file and copy it as code.
  2. Go to react-svgr and make sure the React Native option is selected. Paste the code copied from step 1. This tool will provide the React Native equivalent on the right-hand side.
May 12, 2024

How to link react-native with react-native SVG? ›

Installation and Configuration

First, install the react-native-svg and react-native-svg-transformer packages to your project with the package manager of your choice: yarn add react-native-svg react-native-svg-transformer . Next, update your metro-config. js bundler configuration file.

How to use SVG in react-native Medium? ›

How to Add SVGs to Your React Native App: A Quick and Simple Guide
  1. Step 1: Install the Necessary Packages. To use SVGs in React Native, you need the react-native-svg library. ...
  2. Step 2: Import SVG Components. ...
  3. Step 3: Add Your SVG Code. ...
  4. Step 4: Use SVG Files (Optional) ...
  5. Step 5: Customize and Enjoy!
Aug 5, 2024

Should you use SVG or PNG in react-native? ›

You can always prefer svgs over pngs as the latter are heavy to render. To render svg assets you can use react-native-svg .

How to use SVG image in react-native Typescript? ›

Svg setup
  1. yarn add react-native-svg. Install the pod related to it:
  2. cd ios && pod install. Now we need to install the react-native-svg-transformer to make react-native able to import those files:
  3. yarn add -D react-native-svg-transformer. Replace the metro. config. js code with:
Apr 18, 2020

Why SVG is not loading in react-native? ›

This is because there isn't a built-in React Native component that can render SVGs directly. Because React Native doesn't provide default support for SVGs, we'll have to install a few libraries from the npm package registry.

How to import SVG from a file? ›

Import SVG files
  1. Using the File Import option: Click File > Import > Import to Stage, or Import to Library and select the SVG file.
  2. Drag and drop an SVG file directly on to the stage.
  3. Using SVG assets stored in your CC library: Drag and drop the asset from CC library directly on to stage or your document's library.
May 24, 2023

How to convert SVG to react component? ›

Converting an SVG to a React component involves taking the SVG XML code and transforming it into JSX code that can be rendered by React. This process allows you to import SVGs into your React components and manipulate them just like any other element in your React application.

How do I display SVG in react-native image? ›

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; You should be able to see your SVG rendered in your screen.

How to position SVG in react-native? ›

Every time you want to place SVG element in your app - you should wrap it using <Svg> component. Without this tag other element's won't be visible, because vectors need points. Since points are on x and y axes, we have to define our playground in terms of height and width attributes - it works like canvas for us.

How do I get SVG files in react? ›

SVGs can be imported and used directly as React components in your React code. The image is not loaded as a separate file; rather, it's rendered along with the HTML. A sample use case would look like this: import { ReactComponent as Logo} from './logo.

How do I import SVG content into react? ›

SVGs can be imported and used directly as React components in your React code. The image is not loaded as a separate file; rather, it's rendered along with the HTML. A sample use case would look like this: import { ReactComponent as Logo} from './logo.

How do I upload SVG files to react JS? ›

Import SVG as a React Component (Inline SVG)
  1. import { ReactComponent as MyIcon } from "./icon.svg"
  2. import myIconUrl, { ReactComponent as MyIcon } from "./icon.svg"
  3. <MyIcon /> <MyIcon className="someClassThatWillBeUsedInCSS" alt="icon" />

How to add SVG image in react-native Expo? ›

Note: you'll need to install an Expo package npx expo install react-native-svg . Open React-SVGR, on the "SVG INPUT" tab clear the text you see, then drag-and-drop your . svg file on the "SVG INPUT" tab and that's it.

Top Articles
Hard Times Never Last: Your Financial Recovery Can Start Now - NerdWallet
Maximizing Income with DSO Ambulatory Surgery Billing Expertise
NOAA: National Oceanic &amp; Atmospheric Administration hiring NOAA Commissioned Officer: Inter-Service Transfer in Spokane Valley, WA | LinkedIn
Knoxville Tennessee White Pages
Http://N14.Ultipro.com
Toyota Campers For Sale Craigslist
Ds Cuts Saugus
Byrn Funeral Home Mayfield Kentucky Obituaries
Best Cav Commanders Rok
Simple Steamed Purple Sweet Potatoes
Dexter Gomovies
7543460065
fort smith farm & garden - craigslist
Puretalkusa.com/Amac
Velocity. The Revolutionary Way to Measure in Scrum
Best Uf Sororities
Praew Phat
Osborn-Checkliste: Ideen finden mit System
Saatva Memory Foam Hybrid mattress review 2024
Reborn Rich Kissasian
Governor Brown Signs Legislation Supporting California Legislative Women's Caucus Priorities
Dark Entreaty Ffxiv
Directions To Nearest T Mobile Store
University Of Michigan Paging System
Craigs List Jonesboro Ar
1979 Ford F350 For Sale Craigslist
Cona Physical Therapy
Pixel Combat Unblocked
Tomb Of The Mask Unblocked Games World
Alternatieven - Acteamo - WebCatalog
lol Did he score on me ?
Bridgestone Tire Dealer Near Me
Filmy Met
Craig Woolard Net Worth
Obsidian Guard's Skullsplitter
Dubois County Barter Page
Delta Rastrear Vuelo
Khatrimmaza
Kattis-Solutions
MethStreams Live | BoxingStreams
Desirulez.tv
1400 Kg To Lb
Sephora Planet Hollywood
Dying Light Nexus
Craigslist Mexicali Cars And Trucks - By Owner
Brother Bear Tattoo Ideas
Samsung 9C8
Euro area international trade in goods surplus €21.2 bn
Tommy Gold Lpsg
211475039
Kindlerso
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6406

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.