How to use svg files in React-Native with Typescript (2024)

Vinícius Pacheco Vieira

Posted on

How to use svg files in React-Native with Typescript (2) How to use svg files in React-Native with Typescript (3) How to use svg files in React-Native with Typescript (4) How to use svg files in React-Native with Typescript (5) How to use svg files in React-Native with Typescript (6)

#typescript #tutorial #reactnative

I've faced some struggle using svg files with React-Native so I decided to give my 2 cents on how to configure it without headaches.
The idea for it is that with typescript I've had some trouble doing the whole setup so I thought it could be a good idea to document my exact steps.

For this tutorial I'll use react-native-svg for svg files and use 0.60+ version of React-Native.

Steps

  • Setup from Scratch
  • Svg setup

Setup from Scratch

Let's start with a blank new project and setup all the way until importing and using svg modules into an app.

react-native init myappwithsvg

Now to add typescript to the project:

yarn add --dev typescript @types/jest @types/react @types/react-native @types/react-test-renderer# or for npmnpm install --save-dev typescript @types/jest @types/react @types/react-native @types/react-test-renderer

Next we need to create a tsconfig.json file and add:

{ "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "isolatedModules": true, "jsx": "react", "lib": ["es6"], "moduleResolution": "node", "noEmit": true, "strict": true, "target": "esnext" }, "exclude": [ "node_modules", "babel.config.js", "metro.config.js", "jest.config.js" ]}

Create a separate jest.config.js file:

module.exports = { preset: 'react-native', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],};

And finally change the App.js to App.tsx. From this step forward we are done setting up typescript and we can go to the second step that is to setup the svg modules that allow us to use svg files.

Svg setup

We will install two libraries, react-native-svg and react-native-svg-transformer and configure one after another.
Let's start installing the react-native-svg:

yarn add react-native-svg

Install the pod related to it:

cd ios && pod install

Now we need to install the react-native-svg-transformer to make react-native able to import those files:

yarn add -D react-native-svg-transformer

Replace the metro.config.js code with:

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

If you try to import files from here you will be able but typescript will give you ts error saying that your svg file could not be found.
Create a declarations.d.ts file in the root of your project if you don't have yet. Paste the following code:

declare module "*.svg" { import { SvgProps } from "react-native-svg"; const content: React.FC<SvgProps>; export default content;}

Now we can import svg files just like normal javascript modules. Create a separate folder named assets in your project root and save the dragon svg. Rename the file to dragon.svg to make it easier to import.

How to use svg files in React-Native with Typescript (7)

Now you can import your files and use all feature [react-native-svg] provides to svg files. Here is my example from the dragon file:

/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */import React, {ReactNode} from 'react';import {SafeAreaView, StyleSheet, View, StatusBar} from 'react-native';import DragonSvg from './assets/dragon.svg';const App: () => ReactNode = () => { return ( <> <StatusBar barStyle="dark-content" /> <SafeAreaView> <View style={styles.body}> <DragonSvg height={400} width={400} fill="blue" /> </View> </SafeAreaView> </> );};const styles = StyleSheet.create({ body: { height: '100%', justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', },});export default App;

Running our app on a simulator should result:

How to use svg files in React-Native with Typescript (8)

The full code of this tutorial is in my github repository here. Now your app is capable of importing svg files correctly with Typescript!

Top comments (6)

Subscribe

Mohammed Yasin Mulla

Mohammed Yasin Mulla

  • Joined

Apr 2 '23 • Edited on Apr 2 • Edited

  • Copy link

Thank you,
It is working fine in my react-native project

danielcnascimento

danielcnascimento

👋 I'm a junior dev passionated by learning how to improve every day! I want a JS-based curriculum, so I code it hard 🚀

  • Location

    Brazil, RJ

  • Work

    Software Developer

  • Joined

Mar 18 '21

  • Copy link

Bruh I tried to add a file: index.d.ts

But didn't work for React Native, why it's working on React then?

These types of definitions file don't work on React Native?

tallestlegacy

tallestlegacy

  • Joined

Jun 17 '22

  • Copy link

Bro, the picture is a JS project not a TS
feels like a scam

Valentine Asogwa

Valentine Asogwa

  • Joined

Jan 16 '23

  • Copy link

Work fine for me ...thanks

Marvelous

Marvelous

Pythonista| Web development| Data Science.

  • Location

    Nigeria

  • Work

    Web developer

  • Joined

Jun 10 '22

  • Copy link

This worked great for me. Thanks.

mohammad hassani

mohammad hassani

i'm new in web developing but I believe in the land of desires

  • Education

    computer eng of vru.ac.ir

  • Joined

Jan 9 '22

  • Copy link

it worked for me! thanks!

For further actions, you may consider blocking this person and/or reporting abuse

How to use svg files in React-Native with Typescript (2024)

FAQs

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

How to use SVG files 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 import SVG in TypeScript react? ›

Using an SVG as a component

import { ReactComponent as Logo} from './logo. svg'; import './App. css'; function App() { return ( <div className="App"> <Logo /> </div> ); } export default App; Although this approach is simple to implement, it has some difficulties.

How to use SVG to TS? ›

How to use svg-to-ts
  1. Binaries. ...
  2. Configuration. ...
  3. Passing arguments to the binary. ...
  4. Configure svg-to-ts over package. ...
  5. Configuration file. ...
  6. Converting to a single object ( conversionType==='object' ) ...
  7. Multiple constants - Treeshakable and typesafe with one file ( conversionType==='constants' )
Feb 18, 2024

How do I convert SVG to react-native component? ›

Converting individual SVG files for React Native

Paste the SVG contents from the exported SVG file into React-SVGR and make sure the "native" checkbox is ticked. It will provide output that we can copy and paste into our project.

How to call a 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.

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 make SVG responsive in react? ›

Making SVG Images Responsive in React

In React, you can make an SVG image responsive by controlling its width and height using CSS. To make an SVG image responsive, you first need to ensure that the SVG has a viewBox attribute.

How to use SVG files? ›

Open those SVG files through the web browser's Open option (the Ctrl+O keyboard shortcut). SVG files can be created through Adobe Illustrator, so you can use that program to open the file. Some other Adobe programs that support SVG files include Photoshop, Photoshop Elements, and InDesign programs.

How to use react-native SVG transformer? ›

Installation and configuration
  1. Step 1: Install react-native-svg library. Make sure that you have installed and linked react-native-svg library: ...
  2. Step 2: Install react-native-svg-transformer library. yarn add --dev react-native-svg-transformer.
  3. Step 3: Configure the react native packager. For Expo SDK v40.
Dec 28, 2021

How to use icons in React Typescript? ›

To do so, use import statement like import {FaDev} from "react-icons" . Next import Icons Types which is provided by react-icons it self to work with Typescript else you might get an error as soon as you start using it normally like we do in react-JavaScript. Use import {IconType } from "react-icons" to import types.

How to lazy load SVG in React? ›

Dynamic Import of SVG as a React Component

In the above code, we are using the 'React. lazy' function to import an SVG file named 'logo. svg' as a React component named 'Logo'. The SVG is then rendered inside a 'Suspense' component, which displays a fallback UI while the SVG is loading.

How to use SVG in code? ›

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

How do you embed SVG files? ›

To embed an SVG via an <img> element, you just need to reference it in the src attribute as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML.

How to convert file to SVG? ›

Open your file in Adobe Illustrator. Save your file by using the option “Save As” Once the dialog box is open, name the file and choose “SVG (svg)” from the dropdown “Format” Click on “Save” and wait for a new dialog box to open.

How do I 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 add a local image in react-native? ›

How to use local Images dynamically in React Native
  1. Ex: const ImageDirectory = “Resources/Images”
  2. const ImageName = currentIndex + “. png” //where current Index will be 1,2 etc.
  3. Const ImagePath = ImageDirectory + ImageName.
May 16, 2020

How do I use animated SVG in react-native? ›

Here's what you have to do if you want to add animations to React. First, you need to create an SVG file with SVGator and animate it. This packet uses webview to render the svg so we need to install it. Add the animated SVG in your project.

How to pass props in SVG? ›

TL;DR: We create a single SVG component and pass a name prop to it. The component resolves the viewBox and path values associated with the icon and returns the SVG element. Lets start with adding the name prop to our SVG component and resolve the path for that name prop.

Top Articles
الغاء الحظر في واتساب | طريقة فك الحظر عن رقمك في الواتساب
هل تصل الرسائل بعد رفع الحظر في الواتس؟ اليك الجواب
Craigslist St. Paul
Western Union Mexico Rate
Math Playground Protractor
Mylife Cvs Login
Matthew Rotuno Johnson
Brutál jó vegán torta! – Kókusz-málna-csoki trió
Hmr Properties
Betonnen afdekplaten (schoorsteenplaten) ter voorkoming van lekkage schoorsteen. - HeBlad
Bjork & Zhulkie Funeral Home Obituaries
Dr. med. Uta Krieg-Oehme - Lesen Sie Erfahrungsberichte und vereinbaren Sie einen Termin
Illinois Gun Shows 2022
Tamilrockers Movies 2023 Download
Sport-News heute – Schweiz & International | aktuell im Ticker
Log in or sign up to view
How do I get into solitude sewers Restoring Order? - Gamers Wiki
Earl David Worden Military Service
Caledonia - a simple love song to Scotland
The best firm mattress 2024, approved by sleep experts
Kashchey Vodka
Georgia Cash 3 Midday-Lottery Results & Winning Numbers
Yisd Home Access Center
Thick Ebony Trans
Vernon Dursley To Harry Potter Nyt Crossword
Bn9 Weather Radar
Inkwell, pen rests and nib boxes made of pewter, glass and porcelain.
Fiona Shaw on Ireland: ‘It is one of the most successful countries in the world. It wasn’t when I left it’
Wat is een hickmann?
James Ingram | Biography, Songs, Hits, & Cause of Death
Emily Katherine Correro
Unm Hsc Zoom
Ippa 番号
Crystal Mcbooty
Henry County Illuminate
15 Best Things to Do in Roseville (CA) - The Crazy Tourist
Reese Witherspoon Wiki
What Is A K 56 Pink Pill?
O'reilly's El Dorado Kansas
Craigslist en Santa Cruz, California: Tu Guía Definitiva para Comprar, Vender e Intercambiar - First Republic Craigslist
Nid Lcms
Dwc Qme Database
Cocorahs South Dakota
R: Getting Help with R
Elven Steel Ore Sun Haven
About Us
Canada Life Insurance Comparison Ivari Vs Sun Life
Join MileSplit to get access to the latest news, films, and events!
All Obituaries | Roberts Funeral Home | Logan OH funeral home and cremation
Bloons Tower Defense 1 Unblocked
Latest Posts
Article information

Author: Jeremiah Abshire

Last Updated:

Views: 5974

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jeremiah Abshire

Birthday: 1993-09-14

Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

Phone: +8096210939894

Job: Lead Healthcare Manager

Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.