If you're using React Native with TypeScript, here is the step-by-step solution:
1. Install react-native-svg
npm install react-native-svg
or
yarn add react-native-svg
2. Link native code
cd ios && pod install
3. Install react-native-svg-transformer
npm install --save-dev react-native-svg-transformer
or
yarn add --dev react-native-svg-transformer
4. Configure the react native packager
For React Native v0.59 or newer:
Merge the contents from your project's metro.config.js
file with this config (create the file if it does not exist already).
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"]
}
};
})();
This is how my merged metro.config.js
looks like:
const { getDefaultConfig } = require('metro-config')
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts },
} = await getDefaultConfig()
return {
transformer: {
babelTransformerPath: require.resolve('react-native-svg-transformer'),
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
resolver: {
assetExts: assetExts.filter((ext) => ext !== 'svg'),
sourceExts: [...sourceExts, 'svg'],
},
}
})()
5. TypeScript configuration:
If you are using TypeScript, you need to add this to your declarations.d.ts
file (create one if you don't have one already):
declare module "*.svg" {
import React from 'react';
import { SvgProps } from "react-native-svg";
const content: React.FC<SvgProps>;
export default content;
}
6. Usage
...
import LogSvg from '../assets/images/Logo.svg'
export function LandingScreen(): JSX.Element {
...
return (
<View style={style.mainContainer}>
<LogSvg style={style.logoContainer} />
</View>
)
}
...