Post

React Native: fix Component return number

React Native Application에서 SVG 이미지 파일을 사용할 때 react-native-svg 이외에 react-native-svg-transformer 또한 함께 사용하기를 권고한다. 아래 오류는 이전의 PNG 이미지 파일이 binary code로 변환되는 과정에서 발생하는 오류와 비슷한 문제로 보이며 react-native-svg-transformer을 설치하여 문제를 해결 할 수 있다.

Error Message

 ERROR  Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: number.

Check the render method of `LogInScreen`.

Solution

  1. Install react-native-svg and react-native-svg-transformer

    1
    2
    
    $ npm i react-native-svg
    $ npm i react-native-svg-transformer
    
  2. Set project’s metro.config.js with following config

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    module.exports = {
      transformer: {
        getTransformOptions: async () => ({
          transform: {
            experimentalImportSupport: false,
            inlineRequires: true,
          },
        }),
      },
    };
    
    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"],
        },
      };
    })();
    
  3. Add .svgrrc

    1
    2
    3
    4
    5
    
    {
      "replaceAttrValues": {
        "red": "currentColor"
      }
    }
    

Reference

This post is licensed under CC BY 4.0 by the author.