React Native: How to add a vector icon if it's not in the directory?

425 Views Asked by At

I use vector icons in my React Native app, and I find the available ones in this directory. I need to add an icon that look this this, but there isn't one in the directory. If I download the svg file at that link, is there a way to add it to my app? Or is there a different recommended way to add vector icons that aren't in the directory?

1

There are 1 best solutions below

0
On

Yes, just use 2 libs: react-native-svg-transformer and react-native-svg

  1. Download the svg you want, save it in a folder inside your of project

  2. Install react-native-svg and react-native-transformer:

 yarn add react-native-svg-transformer react-native-svg

or

 npm install react-native-svg react-native-svg
  1. Now, you need configure your project, the babel: Go to the file metro.config.js in the root of your project and merge the contentswith this config (create the file if it does not exist already):
  2. Case use React-Native CLI:
 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"]
     }
   };
 })();

  1. Case use Expo:
  // Learn more https://docs.expo.io/guides/customizing-metro
  const { getDefaultConfig } = require('expo/metro-config');
  
  module.exports = (async () => {
      const {
        resolver: { sourceExts, assetExts }
      } = await getDefaultConfig(__dirname);
      return {
        transformer: {
          babelTransformerPath: require.resolve("react-native-svg-transformer")
        },
        resolver: {
          assetExts: assetExts.filter(ext => ext !== "svg"),
          sourceExts: [...sourceExts, "svg"]
        }
      };
    })();
  1. Now just import the svg that you downloaded in your component as React Component and use:
   import TransparentPokeball from '../../assets/icons/transparent-pokeball.svg';
   ...
 
  <TransparentPokeball
     fill="#000000"
     width={45}
     height={45}
  />

Note:

  • Case use Typescript, you need add type for svg files as like png files, json files...

  • Just create a folder in your project's src with name @types, in it, create another folder with name svg, inside that svg folder, create a file called index.d.ts with the code below:

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

In case there is any doubt, just consult the links of the libraries I sent. they have everything I mentioned above documented.