Transform svg into react-native-svg format

Can anyone recommend a straightforward method for achieving this? I have come across several svg to JSX converters, but unfortunately they do not work in react-native. I am looking for a way to convert the svg code into a format compatible with react-native-svg for displaying in my app. Any suggestions or help would be greatly appreciated. Thank you!

Answer №1

Consider the following alternatives based on the number of files you need to convert:

Option 1 (for few files)

If you have a small number of files, you can copy-paste your svg code into this online tool and select the React Native checkbox. This will generate code compatible with react-native-svg that you can use.

Simply replace the SvgComponent in the code snippet below with the generated code:

import React, { Component } from 'react';
import { View } from 'react-native';
import Svg, { Circle, Path } from 'react-native-svg';

const SvgComponent = props => (
  <Svg viewBox="0 0 48 1" style={props.style}>
    <Path d="M0 0h48v1H0z" fill="#063855" fillRule="evenodd" />
  </Svg>
);

class MySVGIcon extends Component {
  render() {
    const { style } = this.props;
    const component = SvgComponent(style);

    return <View style={style}>{component}</View>;
  }
}

export default MySVGIcon;

Option 2 (for many files)

If you have multiple files, consider embedding them directly in your code using react-native-remote-svg.

You can achieve this as shown in the code snippet below:

import Image from 'react-native-remote-svg';

class MyImageClass extends Component {

  render () {
    // Embed code or read a SVG file...
    const mySVGImage = '<svg width="48px" height="1px" viewBox="0 0 48 1" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><rect id="Rectangle-5" x="25" y="36" width="48" height="1"></rect></svg>';

    return (
        <Image source={{
                          uri: "data:image/svg+xml;utf8," + mySVGImage
                      }}/>
    );
  }
}

Option 3 (the coolest choice)

While not free, PaintCode is a valuable tool for converting svg files and even supports java-script in Version 3+. You can load your svg files into PaintCode to generate code for your app. The interface is user-friendly and allows you to animate objects within the svg file directly from your code.

Answer №2

When developing a react native app with expo, I encountered a similar issue before stumbling upon a solution on react-native-svg. I opted for the XML Option, and here's how I went about it.

STEP 1- Initially, I used this resource convert SVG to JSX for React to convert the SVG to JSX (Sometimes conversion may not be necessary, depending on the icon).

STEP 2- Start by creating a new component file and import react along with

import { SvgXml } from 'react-native-svg'
, then establish a normal functional component inside.

STEP 3- Enclose the converted SVG icon tag in Quotation marks like this

"<svg>some icon code inside</svg>"
and store it in a variable (var, const, let..etc.).

STEP 4- Finally, return

<SvgXml xml={the variable goes here} />
.

STEP 5- Export the component as usual.

Below is an example implementation:

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

function FastRunningIcon(props) {
    const xml = `<svg
    xmlns="http://www.w3.org/2000/svg"
    width="${props.width}"
        height="${props.height}"
        viewBox="0 0 21.244 20"
            >
    <path
    fill="#595959"
    d="M7.379 20a1.21 1.21 0 01-.783-.291.235.235 0 01-.04-.041 1.258 1.258 0 01-.293-1.036 2.179 2.179 0 01.544-1.049c.387-.459 1.089-1.209 2.085-2.231H6.874a1.426 1.426 0 01-1.062-.412 1.263 1.263 0 01-.332-.863 1.166 1.166 0 01.345-.85 1.7 1.7 0 011.01-.425c.454-.05 1.532-.07 2.575-.09h.187c.4-.008.649-.009.869-.01h.506L8.4 8.925 8.38 8.9a2.075 2.075 0 01-.2-1.877 3.3 3.3 0 011.165-1.272l.013-.013L12.412 3.6l-1.221-.957-4.011.094h-.04c-.064 0-.116.007-.168.007a2.209 2.209 0 01-.642-.1 1.271 1.271 0 01-.43-.213.755.755 0 01-.279-.478.014.014 0 00-.006-.006s-.006...
    
    return <SvgXml xml={xml} />
}

export default FastRunningIcon;

Answer №3

If you're looking for a convenient solution to convert your SVG files, check out this helpful tool: https://github.com/MoOx/react-from-svg

This tool not only converts SVG to React Native files but also supports conversion to Reason/ReScript React Native files and React DOM files. Additionally, it offers the option to eliminate fill or strokes attributes from the converted output.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending JSON data from the primary window to the secondary window in Electron - A step-by-step guide

I am currently working with a set of 3 files. index.html: ... <a href="#" onclick="fetch(function(data) {console.log(data); subWindow(data)})">subWindow</a> ... The fetch() function retrieves a callback in JSON format. subWindows.js: let m ...

Unable to utilize the useState hook in TypeScript (Error: 'useState' is not recognized)

Can you identify the issue with the following code? I am receiving a warning from TypeScript when using useState import * as React, { useState } from 'react' const useForm = (callback: any | undefined) => { const [inputs, setInputs] = useS ...

Having trouble retrieving the most recent state on the ReactJS login page

Recently, I've encountered a challenge while working on my React JS project. Specifically, I'm developing a login page where I aim to show an error message when users input invalid credentials. Strangely, even with incorrect details, the login pr ...

What is a creative way to get rid of old content on a webpage using jQuery without relying on the

As I work on my crossword project, I have almost completed it, but encountering a problem. Within my HTML code, I have a select list that loads a .JSON file using Javascript. <form method="post" id="formulaire"> <div class="toto"> <sel ...

Even when using $convert with null conditions and errors, the output will always be NaN

I am currently experiencing an issue with aggregation in MongoDB. When I group the results, sum them, and convert the field to double, I encounter a problem. If there is an error or a null value, I have specified that it should return 0. However, the outpu ...

ui-router: Issues with utilizing the <ui-view> element within a bespoke directive

In my current project, I am utilizing version 0.3.1 of ui-router. Within my custom directive, there is a <ui-view></ui-view> tag present. <div > <button type="button" class="btn btn-primary btn-circle btn-lg pull-left" ui-sref="u ...

Using the MoveToElement and click functions in Protractor with Node.js for automated browser

Trying to click on a checkbox in our application. I have successfully implemented it in Selenium Java using the code below, but struggling to do the same in Protractor Node.js. Any assistance would be appreciated. Selenium- Java : Actions actions ...

Tinted map polygons on Google Maps with an external map shade

Initially, to highlight my polygon in this case, I implemented the following code snippet: Highlight polygon and tint rest of map using Google Maps Below is the Angular code I utilized: var boundaries = []; // defining a large area var overlay ...

What is the best way to submit a dynamically created form within an Angular application?

Hey there! I'm working with a dynamically created form and I need to figure out how to send the form when it's submitted. Any ideas on how to do this would be greatly appreciated! Check out my code on Plunker: Link <form name="MCommForm{{ite ...

I am looking to fetch information from a different Firestore collection by looping through data using a forEach method within an onSnapshot function

I'm struggling to grasp the concept of rendering data from Firestore in my project. I've searched extensively but haven't been able to find a solution that fits my requirements. Background Information In my Firestore database, I have collec ...

Deleting the clone <div> while ensuring the main <div> is kept clear of any remaining data

Initially: https://i.sstatic.net/SLG7O.png After adding a new row and then removing it. https://i.sstatic.net/FegjK.png Why is this happening? When I set val(""), the textbox should have no value. What mistake did I make in my code? Please assist. Her ...

A lesson is what I'm seeking, as I face an Uncaught TypeError: Unable to locate the property 'split' of an undefined value

Although this question has been asked multiple times before, I am a beginner and eager to learn. I would greatly appreciate it if someone could take the time to explain this to me. I have tried to find a solution to this error using the existing answers, b ...

Designing a calendar with a grid template

I am attempting to design a calendar that resembles an actual calendar, but I am facing an issue where all created divs (representing days) are being saved in the first cell. I am not sure how to resolve this. Any help would be greatly appreciated. css . ...

What are the best practices for managing data input effectively?

I am facing a challenge with input validation. I need to restrict the input to only accept strings of numbers ([0-9]) for the entity input field. If anything else is entered, I want to prevent it from overwriting the value and displaying incorrect input. I ...

The error encountered is related to a missing module in react-native-svg: "Module not found: Error: Unable to locate 'react-native/Libraries/Utilities/codegenNativeComponent'"

I have integrated the "react-native-web-linear-gradient": "^1.1.2" library into my project which has a dependency on react-native-svg. For the svg package, I am currently using version ^13.8.0. However, when I attempt to run yarn story ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

Eliminate an item from an array

How can you effectively remove the property "itemType" from the object provided below? { "id": 19, "cost": 10, "items": 10, "numbers": 10, "status": false, "hours": 10, "itemType": { "id": 16, "name": "PC 350", ...

Using Angular 2: Exploring the power of observables for broadcasting events during a forEach loop

Upon testing the service within a forEach loop, I noticed that the parameter I passed to the service ended up being the last one in the iteration. I initially suspected that the issue was due to closures, so I attempted using an anonymous function to add ...

Tips for submitting an Ajax Form with identical Name attributes?

One part of my form consists of input fields with the same 'Name' values that will be stored as an Array. I am attempting to send these values via AJAX to PHP for updating my database. The challenge I'm facing is figuring out how to send t ...

Using React.js to pass data iterated with map function to a modal

I am trying to display my data in a modal when clicking on buttons. The data is currently shown as follows: 1 John watch 2 Karrie watch 3 Karen watch ... like this It is presented in the form of a table with all the 'watch' items being button ...