Skip to main content

Working with SVG and Vector Graphics

1. Installing react-native-svg

Example: Install react-native-svg

npm install react-native-svg
Step Description Command
1 Install the react-native-svg package npm install react-native-svg
2 Link the native dependencies (for React Native < 0.60) react-native link react-native-svg
3 For React Native 0.60+, autolinking handles this automatically npm install react-native-svg
Note: For React Native versions < 0.60, you must manually link the native dependencies using react-native link. For versions >= 0.60, autolinking is supported.

2. Creating SVG Components

Example: Basic SVG Component

<Svg width="100" height="100">
  <Circle cx="50" cy="50" r="40" fill="blue" />
</Svg>
Element Attributes Description
Svg width, height, viewBox Root SVG container element
Circle cx, cy, r, fill Draws a circle with center (cx, cy) and radius r
Rect x, y, width, height, fill Draws a rectangle with top-left corner (x, y)
Path d, fill, stroke Draws complex shapes using path data
Note: All SVG elements must be wrapped in the <Svg> component to render correctly in React Native.

Example: SVG with Gradient

<Svg width="200" height="200">
  <Defs>
    <LinearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
      <Stop offset="0%" stopColor="red" />
      <Stop offset="100%" stopColor="blue" />
    </LinearGradient>
  </Defs>
  <Circle cx="100" cy="100" r="50" fill="url(#gradient)" />
</Svg>

3. Using SVG Icons from Files

SVG icons can be imported directly into React Native components using the react-native-svg library. This approach is useful for integrating custom vector graphics or third-party icon sets.

Property Description Example
import Importing an SVG file as a React component import Icon from './assets/icon.svg';
component Using imported SVG as a component in JSX <Icon width={24} height={24} />

Example: Importing and Using an SVG Icon

import React from 'react';
import { View } from 'react-native';
import Icon from './assets/home-icon.svg';

const HomeScreen = () => {
  return (
    <View style={{ padding: 20 }}>
      <Icon width={32} height={32} fill="#000" />
    </View>
  );
};

export default HomeScreen;
Note: Ensure that the SVG file is properly configured to be compatible with React Native's SVG renderer. Some advanced SVG features may not render correctly.

4. Implementing Animated SVGs

Example: Basic Animated SVG

<Svg height="100" width="100">
  <Circle
    cx="50"
    cy="50"
    r="20"
    fill="blue">
    <Animate
      attributeName="cx"
      from="10"
      to="90"
      dur="2s"
      repeatCount="indefinite"
    />
  </Circle>
</Svg>
Property Description Values Notes
attributeName SVG attribute to animate cx, cy, r, fill Must be a valid SVG attribute
from Starting value of the attribute Number or color Can be any valid SVG value
to Ending value of the attribute Number or color Must match type of from
dur Duration of animation 2s, 500ms Time format: seconds or milliseconds
repeatCount Number of times to repeat indefinite, 1, 3 indefinite for continuous loop
Note: The <Animate> component is part of the react-native-svg library and requires react-native-svg to be installed.
Warning: SVG animations in React Native are limited to basic attribute changes. Complex animations may require Animated API or react-native-reanimated.

Example: Animated Path with Easing

<Svg height="200" width="200">
  <Path
    d="M10 10 L100 100"
    stroke="red"
    strokeWidth="2">
    <Animate
      attributeName="d"
      from="M10 10 L100 100"
      to="M10 10 L150 150"
      dur="1s"
      easing="ease-in-out"
    />
  </Path>
</Svg>

5. Creating Custom Shapes

Example: Custom SVG Shape

<Svg height="100" width="100">
  <Circle cx="50" cy="50" r="40" fill="blue" />
</Svg>
Property Description Values
cx X coordinate of the circle center number
cy Y coordinate of the circle center number
r Radius of the circle number
fill Fill color of the shape string
Note: The <Svg> component must wrap all SVG elements.

6. Using Linear and Radial Gradients

Example: Basic Linear Gradient

<LinearGradient
  x1="0%"
  y1="0%"
  x2="100%"
  y2="0%"
  colors={['#ff0000', '#00ff00', '#0000ff']}
>
  <Rect
    x="10"
    y="10"
    width="200"
    height="100"
    fill="url(#linearGradient)"
  />
</LinearGradient>
Property Values Description
x1 0% | 100% Start X position of the gradient (percentage or absolute)
y1 0% | 100% Start Y position of the gradient (percentage or absolute)
x2 0% | 100% End X position of the gradient (percentage or absolute)
y2 0% | 100% End Y position of the gradient (percentage or absolute)
colors Array<string> List of color stops for the gradient

Example: Radial Gradient

<RadialGradient
  cx="50%"
  cy="50%"
  rx="50%"
  ry="50%"
  colors={['#ffffff', '#000000']}
>
  <Circle
    cx="100"
    cy="100"
    r="50"
    fill="url(#radialGradient)"
  />
</RadialGradient>
Property Values Description
cx 0% | 100% Center X position of the gradient (percentage or absolute)
cy 0% | 100% Center Y position of the gradient (percentage or absolute)
rx 0% | 100% Radius X of the gradient (percentage or absolute)
ry 0% | 100% Radius Y of the gradient (percentage or absolute)
colors Array<string> List of color stops for the gradient

7. Handling SVG Transformations

Property Values Description
transform string Applies a transformation to the SVG element. Supports: rotate(angle), scale(x, y), translate(x, y), skewX(angle), skewY(angle)
rotation number Rotates the element around its center. Equivalent to rotate(angle).
scale number | [number, number] Scales the element. If a single number is provided, it scales uniformly. If an array is used, it scales X and Y separately.
translate [number, number] Translates (moves) the element along X and Y axes.

Example: Applying Transformations to an SVG Path

<Svg height="200" width="200">
  <Path
    d="M10 10 H 90 V 90 H 10 Z"
    fill="blue"
    transform="rotate(45 50 50) scale(1.2)"
  />
</Svg>
Note: Transformations in SVG are applied in the order they appear in the transform attribute. For example, rotate(45) scale(1.2) rotates first and then scales.

Example: Using Transform with Animated Values

import { Animated } from 'react-native';

const AnimatedSvg = Animated.createAnimatedComponent(Svg);
const AnimatedPath = Animated.createAnimatedComponent(Path);

const rotation = new Animated.Value(0);

Animated.loop(
  Animated.timing(rotation, {
    toValue: 360,
    duration: 2000,
    useNativeDriver: true
  })
).start();

<AnimatedSvg height="200" width="200">
  <AnimatedPath
    d="M10 10 H 90 V 90 H 10 Z"
    fill="red"
    transform={`rotate(${rotation} 50 50)`}
  />
</AnimatedSvg>

8. Creating SVG Charts

Example: Basic Bar Chart with React Native SVG

<Svg height="200" width="300">
  <Rect x="10" y="50" width="40" height="100" fill="steelblue" />
  <Rect x="60" y="30" width="40" height="120" fill="steelblue" />
  <Rect x="110" y="70" width="40" height="80" fill="steelblue" />
  <Rect x="160" y="40" width="40" height="110" fill="steelblue" />
  <Rect x="210" y="60" width="40" height="90" fill="steelblue" />
</Svg>
Element Properties Description
Svg height, width Container for SVG elements, defines canvas size
Rect x, y, width, height, fill Draws a rectangle; used for bars in bar charts
Circle cx, cy, r, fill Draws a circle; useful for data points in line charts
Line x1, y1, x2, y2, stroke Draws a line between two points; used for chart gridlines or trend lines
Text x, y, fill Displays text labels on charts (e.g., axis labels or data values)
Note: For more complex charts, consider using libraries like react-native-svg-charts or victory-native.

Example: Line Chart with Data Points

<Svg height="200" width="300">
  <Line x1="10" y1="150" x2="60" y2="100" stroke="#ff0000" strokeWidth="2" />
  <Circle cx="10" cy="150" r="4" fill="#ff0000" />
  <Circle cx="60" cy="100" r="4" fill="#ff0000" />
  <Circle cx="110" cy="120" r="4" fill="#ff0000" />
  <Circle cx="160" cy="80" r="4" fill="#ff0000" />
</Svg>

9. Optimizing SVG Performance

Example: Using react-native-svg with fastRender

import Svg, { Circle, Rect } from 'react-native-svg';

<Svg width="100" height="100" fastRender>
  <Circle cx="50" cy="50" r="40" fill="red" />
  <Rect x="10" y="10" width="80" height="80" fill="blue" />
</Svg>
Property Values Description
fastRender true / false Enables fast rendering for static SVGs. Improves performance by reducing layout calculations.
width number Width of the SVG container. Should be set explicitly to avoid layout shifts.
height number Height of the SVG container. Should be set explicitly to avoid layout shifts.
Note: Setting width and height explicitly prevents layout reflows during rendering.

Example: Pre-caching SVG assets

import { Asset } from 'expo-asset';
import { SvgXml } from 'react-native-svg';

const xmlContent = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" fill="red" /></svg>';

const CachedSvg = () => {
  const [asset, setAsset] = useState(null);

  useEffect(() => {
    Asset.loadAsync(xmlContent).then(setAsset);
  }, []);

  return <SvgXml xml={xmlContent} width="100" height="100" />;
};

Performance Tips

  • Use fastRender for static SVGs to reduce layout overhead.
  • Set width and height explicitly to prevent layout shifts.
  • Preload SVG assets using Asset.loadAsync in Expo.
  • Avoid deeply nested SVG elements to reduce rendering complexity.

10. Using SVGR for Component Generation

SVGR (SVG React Generator) is a tool that converts SVG files into React components automatically. It's particularly useful for integrating vector graphics into React Native applications.

Feature Description Notes
svgr npm install @svgr/cli Install the SVGR CLI tool
CLI Usage svgr --icon --out-dir ./src/components/svg ./assets/icons Converts SVG files to React components with icon support
Configuration { "icon": true, "native": true } Enables native React Native support and icon mode

Example: Converting SVG to React Component

svgr --icon --native --out-dir ./src/components/svg ./assets/icons/home.svg

Example: Generated Component

import * as React from "react";
import { Svg, Path } from "react-native-svg";

function HomeIcon(props) {
  return (
    <Svg
      width={24}
      height={24}
      viewBox="0 0 24 24"
      fill="none"
      {...props}
    >
      <Path
        d="M3 9L12 2L21 9V20C21 20.5304 20.7893 21.0391 20.4142 21.4142C20.0391 21.7893 19.5304 22 19 22H5C4.46957 22 3.96086 21.7893 3.58579 21.4142C3.21071 21.0391 3 20.5304 3 20V9Z"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <Path
        d="M9 22V12H15V22"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </Svg>
  );
}

export default HomeIcon;
Note: The generated component uses react-native-svg which must be installed in your project.
Warning: Ensure that SVG files are properly optimized before conversion to reduce component size and improve performance.

Was this article helpful?