Scalable Vector Graphics (SVG) is an XML based language for describing two-dimensional vector graphics.
Most of the modern browsers are supporting SVG images, but using SVG in React Native app we needs to use the third party package.
react-native-svg
is a npm package which provides SVG support to React Native Apps on both Android and IOs platforms.
To use the SVG image in your project, let’s first install the package.
npm install react-native-svg –save
Now, if you are using react native version above 0.60 than no need to link, but again if you are facing any issue related to this package you can link using the below command.
react-native link react-native-svg
Also install the react-native-svg-transformer library
npm install react-native-svg-transformer --save
React Native SVG transformer allows you to import SVG files in your React Native project the same way that you would in a Web application.
Add a file metro.config.js at the root in your project, if not exists, with the code below.
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"]
}};
})();
Finally, import your SVG like a regular import.
import SVGImage from './assets/images/award.svg';
Also, you can pass width and height props to your component to scale them as per your need.
import React from 'react';
import { View, StyleSheet } from 'react-native';
import SVGImage from './src/assets/images/svg_image.svg';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<SVGImage height={400} width={300} />
</View>
);
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
});
Hope you like this little information about SVG images and how to use it in you React Native project.
If you really like the post please subscribe to protechGuide by clicking here to get notified.
Happy coding! 🙂