## react-native-svg [![Version](https://img.shields.io/npm/v/react-native-svg.svg)](https://www.npmjs.com/package/react-native-svg) [![NPM](https://img.shields.io/npm/dm/react-native-svg.svg)](https://www.npmjs.com/package/react-native-svg) `react-native-svg` provides SVG support to React Native on iOS and Android, and a compatibility layer for the web. [Check out the demo](https://snack.expo.io/@msand/react-native-svg-example) ## Features 1. Supports most SVG elements and properties (Rect, Circle, Line, Polyline, Polygon, G ...). 2. Easy to [convert SVG code](https://svgr.now.sh/) to react-native-svg. - [Installation](#installation) - [Automatically](#automatically) - [Manually](#manually) - [Android](#android-pre-rn-060) - [iOS](#ios-pre-rn-060) - [Troubleshooting](#troubleshooting) - [Opening issues](#opening-issues) - [Usage](#usage) - [Use with content loaded from uri](#use-with-content-loaded-from-uri) - [Use with svg files](#use-with-svg-files) - [Use with xml strings](#use-with-xml-strings) - [Common props](#common-props) - [Supported elements](#supported-elements) - [Svg](#svg) - [Rect](#rect) - [Circle](#circle) - [Ellipse](#ellipse) - [Line](#line) - [Polygon](#polygon) - [Polyline](#polyline) - [Path](#path) - [Text](#text) - [TSpan](#tspan) - [TextPath](#textpath) - [G](#g) - [Use](#use) - [Symbol](#symbol) - [Defs](#defs) - [Image](#image) - [ClipPath](#clippath) - [LinearGradient](#lineargradient) - [RadialGradient](#radialgradient) - [Mask](#mask) - [Pattern](#pattern) - [Marker](#marker) - [Touch Events](#touch-events) - [Serialize](#serialize) - [Run example](#run-example) - [TODO](#todo) - [Known issues](#known-issues) ### Installation #### Automatically ##### With expo-cli With Expo, you'll need to run `expo install react-native-svg` to install this library. Please refer to [Expo docs](https://docs.expo.io/versions/latest/sdk/svg/) for more information or jump ahead to [Usage](#Usage). ##### With react-native-cli 1. Install library from `npm` ```bash yarn add react-native-svg ``` 2. Link native code With autolinking (react-native 0.60+) ```bash cd ios && pod install ``` Pre 0.60 ```bash react-native link react-native-svg ``` # NOTICE: Due to breaking changes in react-native, the version given in the left column (and higher versions) of react-native-svg only supports the react-native version in the right column (and higher versions, if possible). It is recommended to use the version of react given in the peer dependencies of the react-native version you are using. The latest version of react-native-svg should always work in a clean react-native project. | react-native-svg | react-native | | ---------------- | ------------ | | 3.2.0 | 0.29 | | 4.2.0 | 0.32 | | 4.3.0 | 0.33 | | 4.4.0 | 0.38 | | 4.5.0 | 0.40 | | 5.1.8 | 0.44 | | 5.2.0 | 0.45 | | 5.3.0 | 0.46 | | 5.4.1 | 0.47 | | 5.5.1 | >=0.50 | | >=6 | >=0.50 | | >=7 | >=0.57.4 | | >=8 | >=0.57.4 | | >=9 | >=0.57.4 | Or, include [this PR](https://github.com/facebook/react-native/pull/17842) manually for v7+ stability on android for older RN ( [included in 0.57-stable](https://github.com/facebook/react-native/commit/d9f5319cf0d9828b29d0e350284b22ce29985042) and newer). The latest version of v6, v7, v8 and v9 should all work in the latest react-native version. v7 and newer requires the patch for making android thread safe, to get native animation support. #### Manually ##### Android pre RN 0.60 1. `yarn add react-native-svg` In RN 0.60+, this is all you should ever need to do get Android working. Before this, react-native link was responsible for the following steps: 2. Append the following lines to `android/settings.gradle`: ```gradle include ':react-native-svg' project(':react-native-svg').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-svg/android') ``` 3. Insert the following lines inside the dependencies block in `android/app/build.gradle`: ```gradle implementation project(':react-native-svg') ``` 4. Open up `android/app/src/main/java/[...]/MainApplication.java` - Add `import com.horcrux.svg.SvgPackage;` to the imports at the top of the file - Add `new SvgPackage()` to the list returned by the `getPackages()` method. Add a comma to the previous item if there's already something there. ##### iOS pre RN 0.60 [Manual linking](http://facebook.github.io/react-native/docs/linking-libraries-ios.html#manual-linking) To install react-native-svg on iOS visit the link referenced above or do the following (react-native link should do this for you): 1. Open your project in XCode and drag the `RNSVG.xcodeproj` file (located in `.../node_modules/react-native-svg/ios`) into the Libraries directory shown in XCode. 2. Expand the `RNSVG.xcodeproj` file you just added to XCode until you see: `libRNSVG.a` (located in `RNSVG.xcodeproj` > `Products` ) 3. Drag `libRNSVG.a` into the Link Binary With Libraries section (located in Build Phases which may be found at the top of the XCode window) ###### CocoaPods Alternatively, you can use [CocoaPods](https://cocoapods.org/) to manage your native (Objective-C and Swift) dependencies: 1. Add RNSVG to your Podfile (with RN 0.60+ autolinking, this is not needed) ```ruby pod 'RNSVG', :path => '../node_modules/react-native-svg' ``` If `cocoapods` is used and if error `RNSVGImage.m:12:9: 'React/RCTImageLoader.h' file not found` occurs: Add the following entry in Podfile: ```ruby pod 'React', :path => '../node_modules/react-native', :subspecs => [ [...] 'RCTImage', # <-- Add RCTImage ] ``` and run `pod install` from `ios` folder ### Troubleshooting #### Problems with Proguard When Proguard is enabled (which it is by default for Android release builds), it causes runtine error To avoid this, add an exception to `android/app/proguard-rules.pro`: ```bash -keep public class com.horcrux.svg.** {*;} ``` If you have build errors, then it might be caused by caching issues, please try: ```bash watchman watch-del-all rm -fr $TMPDIR/react-* react-native start --reset-cache Or, rm -rf node_modules yarn react-native start --reset-cache ``` #### Unexpected behavior If you have unexpected behavior, please create a clean project with the latest versions of react-native and react-native-svg ```bash react-native init CleanProject cd CleanProject/ yarn add react-native-svg cd ios && pod install && cd .. ``` Make a reproduction of the problem in `App.js` ```bash react-native run-ios react-native run-android ``` # Opening issues Verify that it is still an issue with the latest version as specified in the previous step. If so, open a new issue, include the entire `App.js` file, specify what platforms you've tested, and the results of running this command: ```bash react-native info ``` If you suspect that you've found a spec conformance bug, then you can test using your component in a react-native-web project by forking this codesandbox, to see how different browsers render the same content: If any evergreen brower with significant userbase or other svg user agent renders some svg content better, or supports more of the svg and related specs, please open an issue asap. ### Usage Here's a simple example. To render output like this: ![SVG example](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/svg.png) Use the following code: ```jsx import Svg, { Circle, Ellipse, G, Text, TSpan, TextPath, Path, Polygon, Polyline, Line, Rect, Use, Image, Symbol, Defs, LinearGradient, RadialGradient, Stop, ClipPath, Pattern, Mask, } from 'react-native-svg'; /* Use this if you are using Expo import { Svg } from 'expo'; const { Circle, Rect } = Svg; */ import React from 'react'; import { View, StyleSheet } from 'react-native'; export default class SvgExample extends React.Component { render() { return ( ); } } ``` [Try this on Snack](https://snack.expo.io/@msand/react-native-svg-example) ### Use with content loaded from uri ```jsx import * as React from 'react'; import { SvgUri } from 'react-native-svg'; export default () => ( ); ``` #### CSS Support If remote SVG file contains CSS in ` `; export default () => ; ``` ### Common props: | Name | Default | Description | | ---------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | fill | '#000' | The fill prop refers to the color inside the shape. | | fillOpacity | 1 | This prop specifies the opacity of the color or the content the current object is filled with. | | fillRule | nonzero | The fillRule prop determines what side of a path is inside a shape, which determines how fill will paint the shape, can be `nonzero` or `evenodd` | | stroke | 'none' | The stroke prop controls how the outline of a shape appears. | | strokeWidth | 1 | The strokeWidth prop specifies the width of the outline on the current object. | | strokeOpacity | 1 | The strokeOpacity prop specifies the opacity of the outline on the current object. | | strokeLinecap | 'square' | The strokeLinecap prop specifies the shape to be used at the end of open subpaths when they are stroked. Can be either `'butt'`, `'square'` or `'round'`. | | strokeLinejoin | 'miter' | The strokeLinejoin prop specifies the shape to be used at the corners of paths or basic shapes when they are stroked. Can be either `'miter'`, `'bevel'` or `'round'`. | | strokeDasharray | [] | The strokeDasharray prop controls the pattern of dashes and gaps used to stroke paths. | | strokeDashoffset | null | The strokeDashoffset prop specifies the distance into the dash pattern to start the dash. | | x | 0 | Translate distance on x-axis. | | y | 0 | Translate distance on y-axis. | | rotation | 0 | Rotation degree value on the current object. | | scale | 1 | Scale value on the current object. | | origin | 0, 0 | Transform origin coordinates for the current object. | | originX | 0 | Transform originX coordinates for the current object. | | originY | 0 | Transform originY coordinates for the current object. | ### Supported elements: #### Svg ```jsx ``` Colors set in the Svg element are inherited by its children: ```jsx ``` ![Pencil](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/pencil.png) Code explanation: - The fill prop defines the color inside the object. - The stroke prop defines the color of the line drawn around the object. - The color prop is a bit special in the sense that it won't color anything by itself, but define a kind of color variable that can be used by children elements. In this example we're defining a "green" color in the Svg element and using it in the second Path element via stroke="currentColor". The "currentColor" is what refers to that "green" value, and it can be used in other props that accept colors too, e.g. fill="currentColor". #### Rect The element is used to create a rectangle and variations of a rectangle shape: ```jsx ``` ![Rect](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/rect.png) Code explanation: - The width and height props of the element define the height and the width of the rectangle. - The x prop defines the left position of the rectangle (e.g. x="25" places the rectangle 25 px from the left margin). - The y prop defines the top position of the rectangle (e.g. y="5" places the rectangle 5 px from the top margin). #### Circle The element is used to create a circle: ```jsx ``` ![Rect](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/circle.png) Code explanation: - The cx and cy props define the x and y coordinates of the center of the circle. If cx and cy are omitted, the circle's center is set to (0,0) - The r prop defines the radius of the circle #### Ellipse The element is used to create an ellipse. An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius. ```jsx ``` ![Rect](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/ellipse.png) Code explanation: - The cx prop defines the x coordinate of the center of the ellipse - The cy prop defines the y coordinate of the center of the ellipse - The rx prop defines the horizontal radius - The ry prop defines the vertical radius #### Line The element is an SVG basic shape, used to create a line connecting two points. ```jsx ``` ![Rect](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/line.png) Code explanation: - The x1 prop defines the start of the line on the x-axis. - The y1 prop defines the start of the line on the y-axis. - The x2 prop defines the end of the line on the x-axis. - The y2 prop defines the end of the line on the y-axis. #### Polygon The element is used to create a graphic that contains at least three sides. Polygons are made of straight lines, and the shape is "closed" (all the lines connect up). ```jsx ``` ![Rect](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/polygon.png) Code explanation: - The points prop defines the x and y coordinates for each corner of the polygon #### Polyline The element is used to create any shape that consists of only straight lines: ```jsx ``` ![Rect](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/polyline.png) Code explanation: - The points prop defines the x and y coordinates for each point of the polyline #### Path The element is used to define a path. The following commands are available for path data: - M = moveto - L = lineto - H = horizontal lineto - V = vertical lineto - C = curveto - S = smooth curveto - Q = quadratic Bézier curve - T = smooth quadratic Bézier curveto - A = elliptical Arc - Z = closepath `Note:` All of the commands above can also be expressed with lower letters. Capital letters means absolutely positioned, lower cases means relatively positioned. See [Path document of SVG](https://www.w3.org/TR/SVG/paths.html) to know parameters for each command. ```jsx ``` ![Rect](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/path.png) #### Text The element is used to define text. ```jsx STROKED TEXT ``` ![Text](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/text.png) #### TSpan The element is used to draw multiple lines of text in SVG. Rather than having to position each line of text absolutely, the element makes it possible to position a line of text relatively to the previous line of text. ```jsx tspan line 1 tspan line 2 tspan line 3 12345 6 7 89a delta on text ``` ![TSpan](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/tspan.png) #### TextPath In addition to text drawn in a straight line, SVG also includes the ability to place text along the shape of a element. To specify that a block of text is to be rendered along the shape of a , include the given text within a element which includes an href attribute with a reference to a element. ```jsx We go up and down, then up again ``` ![TextPath](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/text-path.png) #### G The element is a container used to group other SVG elements. Transformations applied to the g element are performed on all of its child elements, and any of its props are inherited by its child elements. It can also group multiple elements to be referenced later with the [<Use />](#use) element. ```jsx Text grouped with shapes ``` ![G](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/g.png) #### Use The element can reuse an SVG shape from elsewhere in the SVG document, including elements and elements. The reused shape can be defined inside the [<Defs>](#defs) element (which makes the shape invisible until used) or outside. ```jsx ``` This example shows a element defined inside a [<Defs>](#defs) element. This makes the invisible unless referenced by a element. Before the element can be referenced, it must have an ID set on it via its id prop. The element references the element via its `href` prop. Notice the # in front of the ID in the prop value. The element specifies where to show the reused shapes via its x and y props. Notice that the shapes inside the element are located at 0,0. That is done because their position is added to the position specified in the element. ![use](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/use.png) #### Symbol The SVG element is used to define reusable symbols. The shapes nested inside a are not displayed unless referenced by a element. ```jsx ``` ![Symbol](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/symbol.png) #### Defs The element is used to embed definitions that can be reused inside an SVG image. For instance, you can group SVG shapes together and reuse them as a single shape. #### Image The element allows a raster image to be included in an Svg componenet. ```jsx HOGWARTS ``` ![Image](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/image.png) #### ClipPath The SVG element defines a clipping path. A clipping path is used/referenced using the clipPath property ```jsx Q ``` ![ClipPath](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/clip-path.png) #### LinearGradient The element is used to define a linear gradient. The element must be nested within a [<Defs>](#defs) tag. The [<Defs>](#defs) tag is short for definitions and contains definition of special elements (such as gradients). Linear gradients can be defined as horizontal, vertical or angular gradients: - Horizontal gradients are created when y1 and y2 are equal and x1 and x2 differ - Vertical gradients are created when x1 and x2 are equal and y1 and y2 differ - Angular gradients are created when x1 and x2 differ and y1 and y2 differ ```jsx ``` Code explanation: - The id prop of the tag defines a unique name for the gradient - The x1, x2, y1,y2 props of the tag define the start and end position of the gradient - The color range for a gradient can be composed of two or more colors. Each color is specified with a tag. The offset prop is used to define where the gradient color begin and end - The fill prop links the ellipse element to the gradient ![LinearGradient](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/lineargradient.png) _NOTICE:_ LinearGradient also supports percentage as prop: ```jsx ``` This result is same as the example before. But it's recommend to use exact number instead; it has performance advantages over using percentages. #### RadialGradient The element is used to define a radial gradient. The element must be nested within a [<Defs>](#defs) tag. The [<Defs>](#defs) tag is short for definitions and contains definition of special elements (such as gradients). ```jsx ``` Code explanation: - The id prop of the tag defines a unique name for the gradient - The cx, cy and r props define the outermost circle and the fx and fy define the innermost circle - The color range for a gradient can be composed of two or more colors. Each color is specified with a tag. The offset prop is used to define where the gradient color begin and end - The fill prop links the ellipse element to the gradient ![RadialGradient](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/radialgradient.png) #### Mask In SVG, you can specify that any other graphics object or ‘G’ element can be used as an alpha mask for compositing the current object into the background. A mask is defined with a ‘Mask’ element. A mask is used/referenced using the ‘mask’ property. A ‘Mask’ can contain any graphical elements or container elements such as a ‘G’. The element must be nested within a [<Defs>](#defs) tag. The [<Defs>](#defs) tag is short for definitions and contains definition of special elements (such as gradients). ```jsx Masked text ``` Code explanation: ![Mask](https://www.w3.org/TR/SVG11/images/masking/mask01.svg) #### Pattern A pattern is used to fill or stroke an object using a pre-defined graphic object which can be replicated ("tiled") at fixed intervals in x and y to cover the areas to be painted. Patterns are defined using a ‘pattern’ element and then referenced by properties ‘fill’ and ‘stroke’ on a given graphics element to indicate that the given element shall be filled or stroked with the referenced pattern. The element must be nested within a [<Defs>](#defs) tag. The [<Defs>](#defs) tag is short for definitions and contains definition of special elements (such as gradients). ```jsx ``` Code explanation: ![Pattern](https://www.w3.org/TR/SVG11/images/pservers/pattern01.svg) #### Marker A marker is a symbol which is attached to one or more vertices of ‘path’, ‘line’, ‘polyline’ and ‘polygon’ elements. Typically, markers are used to make arrowheads or polymarkers. Arrowheads can be defined by attaching a marker to the start or end vertices of ‘path’, ‘line’ or ‘polyline’ elements. Polymarkers can be defined by attaching a marker to all vertices of a ‘path’, ‘line’, ‘polyline’ or ‘polygon’ element. The graphics for a marker are defined by a ‘marker’ element. To indicate that a particular ‘marker’ element should be rendered at the vertices of a particular ‘path’, ‘line’, ‘polyline’ or ‘polygon’ element, set one or more marker properties (‘marker’, ‘marker-start’, ‘marker-mid’ or ‘marker-end’) to reference the given ‘marker’ element. ```jsx ``` Code explanation: ![Marker](https://www.w3.org/TR/SVG11/images/painting/marker.svg) ```jsx import React from 'react'; import { StyleSheet, View } from 'react-native'; import { SvgXml } from 'react-native-svg'; const markerRendering = ` `; export default class App extends React.Component { render() { return ( ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'white', justifyContent: 'center', alignItems: 'center', flex: 1, }, }); ``` ![MarkerDoubled](https://www.w3.org/TR/SVG2/images/painting/marker-doubled.svg) ```jsx import React from 'react'; import { StyleSheet, View } from 'react-native'; import { SvgXml } from 'react-native-svg'; const markerRendering = ` `; export default class App extends React.Component { render() { return ( ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'white', justifyContent: 'center', alignItems: 'center', flex: 1, }, }); ``` ![MarkerRendering](https://www.w3.org/TR/SVG2/images/painting/marker-rendering.svg) Code explanation: #### Touch Events Touch events are supported in react-native-svg. These include: - `disabled` - `onPress` - `onPressIn` - `onPressOut` - `onLongPress` - `delayPressIn` - `delayPressOut` - `delayLongPress` You can use these events to provide interactivity to your react-native-svg components. ```jsx alert('Press on Circle')} /> ``` ![TouchEvents](https://raw.githubusercontent.com/react-native-community/react-native-svg/master/screenshots/touchevents.gif) For more examples of touch in action, checkout the [TouchEvents.js examples](https://github.com/magicismight/react-native-svg-example/blob/master/examples/TouchEvents.js). ### Serialize ```jsx import * as React from 'react'; import { Platform, StyleSheet, TouchableOpacity } from 'react-native'; import { Svg, Rect } from 'react-native-svg'; import ReactDOMServer from 'react-dom/server'; const isWeb = Platform.OS === 'web'; const childToWeb = child => { const { type, props } = child; const name = type && type.displayName; const webName = name && name[0].toLowerCase() + name.slice(1); const Tag = webName ? webName : type; return {toWeb(props.children)}; }; const toWeb = children => React.Children.map(children, childToWeb); export default class App extends React.Component { renderSvg() { return ( ); } serialize = () => { const element = this.renderSvg(); const webJsx = isWeb ? element : toWeb(element); const svgString = ReactDOMServer.renderToStaticMarkup(webJsx); console.log(svgString); }; render() { return ( {this.renderSvg()} ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', backgroundColor: '#ecf0f1', padding: 8, }, }); ``` ### Run example: ```bash git clone https://github.com/magicismight/react-native-svg-example.git cd react-native-svg-example yarn # run Android: react-native run-android # run iOS: react-native run-ios ``` ### TODO: 1. Filters ### Known issues: 1. Unable to apply focus point of RadialGradient on Android.