In this post we will see how you can use SVG images in a react native application.
In React Native, normal images can be rendered without any additional changes, rendering an SVG requires additional configurations.
In your react native application, first install the following packages to use SVG images.
npm i react-native-svg
npm i react-native-svg-transformer
Enter into the android folder -> app folder -> build.gradle
and add the following line at the end of the file.
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
Go inside the iOS folder and run pod install.
After installing the packages and implementing the above steps, enter into this metro.config.js
file and copy and paste the below code to make sure SVG files are rendered properly.
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'],
},
};
})();
Lets take you have a SVG called logo.svg, what we have to do is we have to import it in your file and use it as a normal tag with height and width as a prop. You can see the code example below.
import {View} from 'react-native';
import React from 'react';
import Logo from './logo.svg';
const App = () => {
return (
<View>
<Logo height={45} width={45} />
</View>
);
};
export default App;
You should be able to see your SVG rendered in your screen. This is how you use SVGs in your react native application.
To know more about React & React Native you can checkout my courses in Udemy.
https://www.udemy.com/course/react-native-for-absolute-beginners-with-react-hooks/
Top comments (1)
The
metro.config.js
instructions here might need a fix.