Add an SVG in React Native with Expo

Tiempo de lectura: 2 minutos

We will learn today how to add an SVG image in React Native using Expo.

The first thing we will do is install the necessary dependencies:

First react-native-svg

html

expo install react-native-svg

And now we installreact-native-svg-transformer

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

We need to configure react-native-svg-transformer.

To do this, we open the metro.config.js file and add:

const { getDefaultConfig } = require("expo/metro-config");module.exports = (() => { const config = getDefaultConfig(__dirname); const { transformer, resolver } = config; config.transformer = { ...transformer, babelTransformerPath: require.resolve("react-native-svg-transformer") }; config.resolver = { ...resolver, assetExts: resolver.assetExts.filter((ext) => ext !== "svg"), sourceExts: [...resolver.sourceExts, "svg"] }; return config;})();

And if we use TypeScript, we need to add this code inside the declarations.d.ts file (create it if you don’t have one).

declare module "*.svg" { import React from "react"; import { SvgProps } from "react-native-svg"; const content: React.FC<SvgProps>; export default content;}

We are now going to test it.

First, we saved this SVG test:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /></svg>

This is a circle:

You save it with the name circle.svg.

Once saved, you will load it into your component in the following way:

First, you import it:

import Circle from './assets/circle.svg';

And use it as if it were a component:

  

Once implemented, we need to make a new build.

Leave a Comment