How to use SVG images in react-native expo app

What are SVGs?

SVG stands for Scalable Vector Graphics. It is an image format that supports infinite resizing and scalability. This means that SVG images can be stretched and resized however we want without compromising on quality. There are many benefits of using SVGs some of which include performance, file size, and style control. I found a very good blog post that explains these benefits here: Benefits of using SVG

Using SVGs in React-native application

  1. Create new expo app

    expo init new-expo-app
    
  2. Move into the new-expo-app folder

    cd new-expo-app
    

    and add 'react-native-svg'

    yarn add react-native-svg
    

    This package will provide SVG support for our react-native app.
    Read more about it here: React-native-svg

  3. Import your SVG image the assets folder
    Create a svgComponent.js file
    Paste this into svgComponent.js:

    import React from "react";
    import { SvgXml } from "react-native-svg";  
    export default function SvgComponent(){  
      const svgMarkup = `<CONTENT OF SVG FILE>`;
      const SvgImage = () => <SvgXml xml={svgMarkup} width="301px" />;  
    
      return <SvgImage />;
    }
    
  4. Open the SVG file, copy its content and use it to replace <CONTENT OF SVG FILE>
    Your svgComponent.js file should look like this: Screenshot 2020-05-22 at 07.44.37.png

  5. You can now import and use your new SVG component wherever you want like a normal React component. Like this.
    import React from "react";
    import { StyleSheet, Text, View } from "react-native";
    import SvgComponent from "./svgComponent";
    export default function App() {
    return (
      <View style={styles.container}>
        <SvgComponent />
      </View>
    );
    }
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: "#fff",
        alignItems: "center",
        justifyContent: "center",
      },
    });
    

And that is all. I hope you find this helpful? See you in my next post

Link to demo repo: React-native-svg-sample

No Comments Yet