Load SVG files in React Native.
Limitations: React Native's packager does not currently support running the transformer for .svg
file extension. That is why a .svgx
file extension should be used instead for your SVG files. This will hopefully be fixed in the future versions of React Native. Read more: facebook/metro/issues/176#issuecomment-393202582
Demo app: react-native-svg-example
Make sure that you have installed and linked react-native-svg
library:
https://github.com/react-native-community/react-native-svg#installation
yarn add --dev react-native-svg-transformer
Add this to your rn-cli.config.js
(make one if you don't have one already):
module.exports = {
getTransformModulePath() {
return require.resolve("react-native-svg-transformer");
},
getSourceExts() {
return ["js", "jsx", "svgx"];
}
};
...or if you are using Expo, in app.json
:
{
"expo": {
"packagerOpts": {
"sourceExts": ["js", "jsx", "svgx"],
"transformer": "node_modules/react-native-svg-transformer/index.js"
}
}
}
First make sure that you rename your .svg
file to .svgx
.
Import your .svgx
file inside a React component:
import Logo from "./logo.svgx";
You can then use your image as a component:
<Logo width={120} height={40} />
In addition to React Native, this transfomer depends on the following libraries: