Using SVG in Latest React Native Version 0.57
--
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:
HAPPY CODING…