• Stars
    star
    794
  • Rank 55,388 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🎨 A React component that injects SVG into the DOM.

react-svg

npm version build status coverage status npm downloads minzipped size

A React component that injects SVG into the DOM.

Background | Basic Usage | Live Examples | API | Installation | FAQ | License

Background

Let's say you have an SVG available at some URL, and you'd like to inject it into the DOM for various reasons. This module does the heavy lifting for you by delegating the process to @tanem/svg-injector, which makes an AJAX request for the SVG and then swaps in the SVG markup inline. The async loaded SVG is also cached, so multiple uses of an SVG only require a single server request.

Basic Usage

import { createRoot } from 'react-dom/client'
import { ReactSVG } from 'react-svg'

const container = document.getElementById('root')
const root = createRoot(container)
root.render(<ReactSVG src="svg.svg" />)

Live Examples

API

Props

  • src - The SVG URL.
  • afterInjection(svg) - Optional Function to call after the SVG is injected. svg is the injected SVG DOM element. If an error occurs during execution it will be routed to the onError callback, and if a fallback is specified it will be rendered. Defaults to () => {}.
  • beforeInjection(svg) - Optional Function to call just before the SVG is injected. svg is the SVG DOM element which is about to be injected. If an error occurs during execution it will be routed to the onError callback, and if a fallback is specified it will be rendered. Defaults to () => {}.
  • desc - Optional String used for SVG <desc> element content. If a <desc> exists it will be replaced, otherwise a new <desc> is created. Defaults to '', which is a noop.
  • evalScripts - Optional Run any script blocks found in the SVG. One of 'always', 'once', or 'never'. Defaults to 'never'.
  • fallback - Optional Fallback to use if an error occurs during injection, or if errors are thrown from the beforeInjection or afterInjection functions. Can be a string, class component, or function component. Defaults to null.
  • httpRequestWithCredentials - Optional Boolean indicating if cross-site Access-Control requests for the SVG should be made using credentials. Defaults to false.
  • loading - Optional Component to use during loading. Can be a string, class component, or function component. Defaults to null.
  • onError(error) - Optional Function to call if an error occurs during injection, or if errors are thrown from the beforeInjection or afterInjection functions. error is an unknown object. Defaults to () => {}.
  • renumerateIRIElements - Optional Boolean indicating if SVG IRI addressable elements should be renumerated. Defaults to true.
  • title - Optional String used for SVG <title> element content. If a <title> exists it will be replaced, otherwise a new <title> is created. Defaults to '', which is a noop.
  • useRequestCache - Optional Use SVG request cache. Defaults to true.
  • wrapper - Optional Wrapper element types. One of 'div', 'span' or 'svg'. Defaults to 'div'.

Other non-documented properties are applied to the outermost wrapper element.

Example

<ReactSVG
  afterInjection={(svg) => {
    console.log(svg)
  }}
  beforeInjection={(svg) => {
    svg.classList.add('svg-class-name')
    svg.setAttribute('style', 'width: 200px')
  }}
  className="wrapper-class-name"
  desc="Description"
  evalScripts="always"
  fallback={() => <span>Error!</span>}
  httpRequestWithCredentials={true}
  loading={() => <span>Loading</span>}
  onClick={() => {
    console.log('wrapper onClick')
  }}
  onError={(error) => {
    console.error(error)
  }}
  renumerateIRIElements={false}
  src="svg.svg"
  title="Title"
  useRequestCache={false}
  wrapper="span"
/>

Installation

⚠️This library depends on @tanem/svg-injector, which uses Array.from(). If you're targeting browsers that don't support that method, you'll need to ensure an appropriate polyfill is included manually. See this issue comment for further detail.

$ npm install react-svg

There are also UMD builds available via unpkg:

For the non-minified development version, make sure you have already included:

For the minified production version, make sure you have already included:

FAQ

Why are there two wrapping elements?

This module delegates it's core behaviour to @tanem/svg-injector, which requires the presence of a parent node when swapping in the SVG element. The swapping in occurs outside of React flow, so we don't want React updates to conflict with the DOM nodes @tanem/svg-injector is managing.

Example output, assuming a div wrapper:

<div> <!-- The wrapper, managed by React -->
  <div> <!-- The parent node, managed by @tanem/svg-injector -->
    <svg>...</svg> <!-- The swapped-in SVG, managed by @tanem/svg-injector -->
  </div>
</div>

See:

Related issues and PRs:

License

MIT

More Repositories

1

react-nprogress

⌛ A React primitive for building slim progress bars.
TypeScript
402
star
2

express-bookshelf-realworld-example-app

🐳 An Express and Bookshelf based backend implementation of the RealWorld API Spec.
JavaScript
98
star
3

svg-injector

💉 Fast, caching, dynamic inline SVG DOM injection library.
TypeScript
94
star
4

generator-typescript-react-lib

🔩 A Yeoman generator for React libs written with Typescript.
JavaScript
18
star
5

state-machines-in-react

🔁 A small React, xstate and Framer Motion demo.
TypeScript
15
star
6

media-query-facade

😷 A nicer JavaScript media query API.
JavaScript
12
star
7

react-salvager

♻️ Reuse row elements when displaying large datasets.
JavaScript
7
star
8

react-redux-playground

🎡 Messing about with React and Redux.
JavaScript
5
star
9

express-backbone-boilerplate

🚧 Sample app built using Express and Backbone plus a few friends.
JavaScript
5
star
10

skyline

🌆 A bar graph that displays information in real time using canvas.
JavaScript
5
star
11

hbs-svg

🚲 Generate Handlebars helpers for optimised inline SVG.
JavaScript
3
star
12

stweam

🌈 Returns tweet data from the public Twitter stream.
JavaScript
3
star
13

chirp

🐦 Stream tweet data from Twitter's public stream all the way through to the browser.
JavaScript
3
star
14

use-document-title

🎣 A React hook that sets the current title of the document.
JavaScript
3
star
15

tanem-scripts

🔩 Common scripts for my projects.
TypeScript
3
star
16

shelljs-plugin-authors

🐚 A ShellJS plugin for generating a nicely formatted list of authors.
JavaScript
2
star
17

salvager

♻️ Reuse row elements when displaying large datasets.
JavaScript
2
star
18

infector

💉 Dependency injection for Node.js and the browser.
JavaScript
2
star
19

default-avatar-helper

:bowtie: A helper for creating default avatars.
JavaScript
2
star
20

sick-fits-frontend

👕 [WIP] A frontend implementation of Wes Bos' Advanced React course.
JavaScript
2
star
21

hackernews-node

📰 A GraphQL API for a Hacker News clone.
TypeScript
2
star
22

webpack-scaffold

A little webpack setup.
JavaScript
1
star
23

karma-protractor-demo

Karma & Protractor test runner demo.
JavaScript
1
star
24

css-revealer

👀 Reveal CSS selector usage within HTML templates.
JavaScript
1
star
25

mtt

🎵 .(m)3u8 (t)o (t)racklist
JavaScript
1
star
26

archiver-webpack-plugin

📁 A webpack plugin that generates zip archives.
TypeScript
1
star
27

parker-loader

📋 Output a stylesheet analysis report using parker and webpack.
JavaScript
1
star
28

jest-prettyhtml-matchers

🃏 Custom Jest snapshot matchers that use prettyhtml to format strings.
TypeScript
1
star
29

tweening-counter

🔢 A counter that uses a timing function to move towards it's destination.
JavaScript
1
star