Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load local svg file with react-native-svg library

I am trying to load a local SVG file in react-native with a react-native-svg library, I have already installed it but I can't figure out how to do it with local svg files. the file is located in "./assets/bg.svg" and i am using expo. please write the exact code if you know.

like image 841
Habib Mhamadi Avatar asked Jan 06 '20 03:01

Habib Mhamadi


People also ask

How do I use SVGs in react-native with Reacto?

Converting individual SVG files for React Native It takes an SVG as input then can transform it into another format, including a format that works with React. Paste the SVG contents from the exported SVG file into React-SVGR and make sure the "native" checkbox is ticked.


Video Answer


1 Answers

For loading react-native-svg with local images, you should also install react-native-svg-transformer on top of it, which you can do in your project with:

npm install react-native-svg-transformer

Afterwards you should, as per the docs (for React Native v0.57 or newer / Expo SDK v31.0.0 or newer):

1. Merge the contents from your project's metro.config.js file with this config (create the file if it does not exist already).

metro.config.js:


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

2. If you are using Expo, you also need to add this to app.json:

app.json:

  "expo": {
    "packagerOpts": {
      "config": "metro.config.js",
      "sourceExts": [
        "expo.ts",
        "expo.tsx",
        "expo.js",
        "expo.jsx",
        "ts",
        "tsx",
        "js",
        "jsx",
        "json",
        "wasm",
        "svg"
      ]
    }
  }
}

3. Finally, a minimal application would look like this:

App.js:

import React from 'react';
import {View} from 'react-native';
import Bg from "./assets/bg.svg";

export default function App() {
    return (
        <View>
            <Bg width={"100%"} height={"100%"} />
        </View>
    );
}
like image 68
Fabio Avatar answered Oct 05 '22 23:10

Fabio