Using SVG in Latest React Native Version 0.57

Image for post
Image for post
SVG with React Native

SVG is a vector format that can scale to any size without losing quality, and it can do this while having a comparatively low file-size too. SVG is amazing like that and preferred implementation on React Native Platform.

Process:
1) Install the Popular React Native SVG Library

npm install react-native-svg@latest --save

2) Link the Library without a miss.

react-native link react-native-svg

3) Install SVG Transformer, which converts the SVG files into React Components during compilation

npm install react-native-svg-transformer --save

4) Create a file if not present name “ rn-cli.config.js” and add the following.

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"]
}};
})();

5) Create a file if not present name “ webpack.config.js ” and add the following.

const webpack = require("webpack"); 
module.exports = {
entry: ["react-hot-loader/patch", "./index.web.js"],
devServer: { hot: true },
plugins: [ new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin() ],
module: {
rules: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
babelrc: false,
presets: [
"@babel/preset-env",
"react",
"module:metro-react-native-babel-preset" ],
plugins: ["react-hot-loader/babel"]
}},
{test: /\.svg$/,
exclude: /node_modules/,
use: [{
loader: "@svgr/webpack"
}]}]},
resolve: {
alias: {
"react-native": "react-native-web"}, extensions: [".web.js", ".js", ".web.jsx", ".jsx"],
mainFields: ["browser", "main"]
}};

6) Import the SVG as a component

import MySVG from '/image/svgname.svg'
class MyComponent implements React.Component {
render(){
return (
<View>
<MySVG height={100} width={100}/>
</View>
);
}
}

7) Important Notes:
a) Remove all the comments from the SVG File.
b) Titles in the SVG are to be removed (as of now)

Result:

Image for post
Image for post

HAPPY CODING…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store