How to show SVG file on React Native?

后端 未结 13 1571
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 11:13

I want to show svg files (I have bunch of svg images) but the thing I couldn\'t find the way to show. I tried to use Image and Use componen

相关标签:
13条回答
  • 2020-12-12 11:42

    you can do this using a simple way

    first, you should take installation,

    1. npm install -s react-native-svg
    2. react-native link react-native-svg
    3. npm install -s react-native-svg-transformer

    then, you should add the following code in your metro.config.js file

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

    after that, you should create a new file in your root directory with the name of declarations.d.js with the following code

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

    Finally, This is a import mathod

    import USER from "../../assets/icons/user.svg"

    and, this is for jsx

    <USER width="100%" height="100%"/>

    0 讨论(0)
  • 2020-12-12 11:47

    After trying many ways and libraries I decided to create a new font (with Glyphs or this tutorial) and add my SVG files to it, then use "Text" component with my custom font.

    Hope this helps anyone that has the same problem with SVG in react-native.

    0 讨论(0)
  • 2020-12-12 11:50

    All these solutions are absolutely horrid. Just convert your SVG to a PNG and use the vanilla <Image/> component. The fact that react-native still does not support SVG images in the Image component is a joke. You should never install an additional library for such a simple task. Use https://svgtopng.com/

    0 讨论(0)
  • 2020-12-12 11:54
    import React from 'react'
    import SvgUri from 'react-native-svg-uri';
    
    export default function Splash() {
      return (
        <View style={styles.container}>
          {/* provided the svg file is stored locally */}
          <SvgUri
            width="400"
            height="200"
            source={require('./logo.svg')}
          />
          {/* if the svg is online */}
          <SvgUri
            width="200"
            height="200"
            source={{ uri: 'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg' }}
          />
    
          <Text style={styles.logoText}>
            Text
          </Text>
        </View>
      )
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      logoText: {
        fontSize: 50
      }
    });
    
    0 讨论(0)
  • 2020-12-12 11:56

    I had the same problem. I'm using this solution I found: React Native display SVG from a file

    It's not perfect, and i'm revisiting today, because it performs a lot worse on Android.

    0 讨论(0)
  • 2020-12-12 11:59

    Use https://github.com/kristerkari/react-native-svg-transformer

    In this package it is mentioned that .svg files are not supported in React Native v0.57 and lower so use .svgx extension for svg files.

    For web or react-native-web use https://www.npmjs.com/package/@svgr/webpack


    To render svg files using react-native-svg-uri with react-native version 0.57 and lower, you need to add following files to your root project

    Note: change extension svg to svgx

    step 1: add file transformer.js to project's root

    // file: transformer.js
    
    const cleanupSvg = require('./cleanup-svg');
    
    const upstreamTransformer = require("metro/src/transformer");
    
    // const typescriptTransformer = require("react-native-typescript-transformer");
    // const typescriptExtensions = ["ts", "tsx"];
    
    const svgExtensions = ["svgx"]
    
    // function cleanUpSvg(text) {
    //   text = text.replace(/width="([#0-9]+)px"/gi, "");
    //    text = text.replace(/height="([#0-9]+)px"/gi, "");
    //    return text;
    // }
    
    function fixRenderingBugs(content) {
      // content = cleanUpSvg(content); // cleanupSvg removes width and height attributes from svg
      return "module.exports = `" + content + "`";
    }
    
    
    module.exports.transform = function ({ src, filename, options }) {
      // if (typescriptExtensions.some(ext => filename.endsWith("." + ext))) {
      //  return typescriptTransformer.transform({ src, filename, options })
      // }
    
      if (svgExtensions.some(ext => filename.endsWith("." + ext))) {
        return upstreamTransformer.transform({
          src: fixRenderingBugs(src),
          filename,
          options
        })
      }
    
      return upstreamTransformer.transform({ src, filename, options });
    }
    
    

    step 2: add rn-cli.config.js to project's root

    module.exports = {
        getTransformModulePath() {
          return require.resolve("./transformer");
        },
        getSourceExts() {
          return [/* "ts", "tsx", */ "svgx"];
        }
      };
    

    The above mentioned solutions will work in production apps too ✅

    0 讨论(0)
提交回复
热议问题