Git Product home page Git Product logo

react-svg's Introduction

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

react-svg's People

Contributors

chrisgarber-medlever avatar danilo-zekovic avatar deadbeef404 avatar dependabot[bot] avatar faceleg avatar illberoy avatar petetnt avatar projectbarks avatar prototypealex avatar renovate-bot avatar renovate[bot] avatar ronperris avatar steven-wolfman avatar tanem avatar tgroutars avatar tianxiumei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-svg's Issues

Uncaught TypeError: Cannot read property 'replaceChild' of null(...)

Getting this error when using this package. Possible conflict with the YouTube Player API?

index.js:541 Uncaught TypeError: Cannot read property 'replaceChild' of null(…)
(anonymous function) @ index.js:541
loadSvg @ index.js:256
injectElement @ index.js:399
SVGInjector @ index.js:599
updateSVG @ index.js:132
componentDidUpdate @ index.js:122
invokeComponentDidUpdateWithTimer @ ReactCompositeComponent.js:75
notifyAll @ CallbackQueue.js:71
close @ ReactReconcileTransaction.js:85
closeAll @ Transaction.js:208
perform @ Transaction.js:155
perform @ Transaction.js:142
perform @ ReactUpdates.js:94
flushBatchedUpdates @ ReactUpdates.js:177
closeAll @ Transaction.js:208
perform @ Transaction.js:155
batchedUpdates @ ReactDefaultBatchingStrategy.js:67
enqueueUpdate @ ReactUpdates.js:205
enqueueUpdate @ ReactUpdateQueue.js:29
enqueueSetState @ ReactUpdateQueue.js:214
ReactComponent.setState @ ReactComponent.js:68
onHeroReady @ HeroBGVideo.jsx:68
YouTube._this.onPlayerReady @ YouTube.js:104
Sister.sister.trigger @ sister.js:53
events.(anonymous function) @ YouTubePlayer.js:43
g.I @ www-widgetapi.js:80
g.l @ www-widgetapi.js:114
g.J @ www-widgetapi.js:132
W.g @ www-widgetapi.js:124
Jb.f @ www-widgetapi.js:100

only rendering one svg icon

Very new to SVG's, so please tell me what I'm doing wrong.

Issue seems to be that while im importing completely different SVGs from different locations, it will only render one svg type. So if I'm trying to render a ticket, a trash can and a card, it will render 3 trashcans. Etc.

I have tested them individually, and they work correctly.

Example below will render three of the same icons, despite the fact that all three are completely different.

import React, { Component } from "react";
import ReactSVG from 'react-svg';
import ticketHubOff from '../../nav/tickethub_active_md.svg'
import test1 from '../../nav/cardhub_active_md.svg';
import test2 from '../../nav/citations_inactive_md.svg';

const render1 = () => (
  <ReactSVG
    path={ticketHubOff}
    className="ticketHubOff1"
    wrapperClassName="svg-icon1"
  />
)

const render2 = () => (
  <ReactSVG
    path={test1}
    className="ticketHubOff2"
    wrapperClassName="svg-icon2"
  />
)

const render3 = () => (
  <ReactSVG
    path={test2}
    className="ticketHubOff3"
    wrapperClassName="svg-icon3"
  />
)

class IconsLibrary extends Component {
  render() {
    return (
        <div className="Content--Example--Row">
          {render1()}
          {render2()}
          {render3()}
        </div>
    );
  }
}

advanced svg

Hi, i have a problem with injecting one svg.file thats made in inkscape with some extra visuals.

when i injected it i lose all the special effects. Anyone got a sulotion for this?

react-svg throws error if another component has an error

react-svg started reporting the following error when there was an unrelated error on another component's componentWillMount method (a property access on undefined).

Only this was reported and I couldn't see where the original error was, which made debugging it pretty difficult:

index.js:90 Uncaught TypeError: Cannot read property 'removeChild' of undefined
    at ReactSVG.removeSVG (index.js:90)
    at ReactSVG._this.refCallback (index.js:49)
    at detachRef (ReactRef.js:29)
    at Object.ReactRef.detachRefs (ReactRef.js:84)
    at Object.unmountComponent (ReactReconciler.js:77)
    at ReactCompositeComponentWrapper.unmountComponent (ReactCompositeComponent.js:417)
    at Object.unmountComponent (ReactReconciler.js:78)
    at Object.unmountChildren (ReactChildReconciler.js:146)
    at ReactDOMComponent.unmountChildren (ReactMultiChild.js:371)
    at ReactDOMComponent.unmountComponent (ReactDOMComponent.js:990)

Unfortunately this is a stopper error and I had to switch libraries. Thought I should report it anyways.
Thank you

loading component jump up

hi @tanem

i make a simple demo with loading component by using the latest version(7.1.0).
the loading component(just div with simple css) is jump up before the real svg img arrives
is there sth i can do to cancel this effect?

jump-example

Additional DIV over the SVG

Hello,

i have code in project like this

<ReactSVG path={imagePath} className="mobile-service-box__contact-icon"/>;

but the result is wrapped in two DIVs why is that ? i dont want these DIVs

<div><div><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" width="216px" height="146px" viewBox="0 0 216 146" enable-background="new 0 0 216 146" xml:space="preserve" class="injected-svg mobile-service-box__contact-icon" data-src="/content/dam/svg/microphone28.svg"> <g> <path d="M108,99.07c7.17,0,13.307-2.553,18.412-7.657S134.07,80.17,134.07,73V31.286c0-7.17-2.551-13.307-7.658-18.413 C121.307,7.768,115.17,5.214,108,5.214s-13.307,2.554-18.413,7.659s-7.659,11.243-7.659,18.413V73 c0,7.17,2.554,13.309,7.659,18.413S100.83,99.07,108,99.07z"></path> <path d="M153.38,58.905c-1.03-1.032-2.254-1.548-3.666-1.548s-2.634,0.516-3.666,1.548c-1.032,1.032-1.548,2.254-1.548,3.666V73 c0,10.049-3.572,18.643-10.714,25.786C126.645,105.929,118.049,109.5,108,109.5s-18.644-3.571-25.787-10.714 C75.071,91.645,71.5,83.049,71.5,73V62.571c0-1.412-0.516-2.634-1.548-3.666c-1.032-1.032-2.253-1.548-3.666-1.548 s-2.635,0.516-3.667,1.548c-1.032,1.032-1.548,2.254-1.548,3.666V73c0,12.004,4.006,22.446,12.017,31.326 c8.011,8.88,17.91,13.972,29.697,15.275v10.756H81.928c-1.412,0-2.634,0.516-3.666,1.548c-1.032,1.032-1.548,2.254-1.548,3.666 c0,1.411,0.516,2.635,1.548,3.666c1.032,1.032,2.254,1.549,3.666,1.549h52.142c1.412,0,2.636-0.517,3.666-1.549 c1.033-1.031,1.55-2.255,1.55-3.666c0-1.412-0.517-2.634-1.55-3.666c-1.03-1.032-2.254-1.548-3.666-1.548h-20.855v-10.756 c11.785-1.303,21.684-6.395,29.696-15.275c8.012-8.88,12.019-19.322,12.019-31.326V62.571 C154.93,61.159,154.413,59.938,153.38,58.905z"></path> </g> </svg></div></div>

Fill URL being converted on render

When react-svg renders this:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1365.7 639.8"><defs><linearGradient id="b" x1="430.8" y1="197.7" x2="1480.8" y2="376.3" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#aaa9b2"/><stop offset="1" stop-color="#90919c"/></linearGradient><linearGradient id="a" x1="159.6" y1="44.4" x2="1094.1" y2="443.5" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#4adec2"/><stop offset="1" stop-color="#007cc3"/></linearGradient><linearGradient id="c" x1="190.4" y1="-27.9" x2="1125" y2="371.1" xlink:href="#a"/><linearGradient id="d" x1="236.4" y1="-135.6" x2="1170.9" y2="263.4" xlink:href="#a"/><linearGradient id="e" y1="411.5" x2="1365.7" y2="411.5" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#534e55"/><stop offset="1" stop-color="#413f4a"/></linearGradient><linearGradient id="f" y1="437" x2="1188.7" y2="437" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#363032"/><stop offset="1" stop-color="#1b1718"/></linearGradient></defs><path d="M1365.7 262.6v258.3L1211.2 460c-15.6-2.6-28.8-12.4-43-19.3-33.4-16.3-78-21.3-93.6-55-4.3-9.2-6-20.1-13.6-26.8-14-12.4-36-2-54.4-4.6-22.7-3.2-37.1-25-55.8-38.2-31-21.9-74.6-20.2-103.8-44.4-18.3-15.1-32.8-40.8-56.4-39.5-30.7 1.8-37.1 43.7-56 67.9-4 5-9.9 9.7-16 8.3-5-1.1-8.2-5.8-12.6-8.4-21.5-12.8-40 29-65 27.7-16-.8-24.6-18.5-30-33.6a166.8 166.8 0 0 1-67.2 26.3 153 153 0 0 0-84.6-51.8c-13.5-3-28.6-4.7-39.8-11.9a73.2 73.2 0 0 1 42.4-17c8.4-.2 16.7 1.4 25 1.1 24.3-.8 45.2-17.5 69.1-21.7 15.1-2.6 30.6-.2 45.9.4a190.5 190.5 0 0 0 99-23.4c4.8-2.6 10-5.6 15.4-4.9 6.6.8 11.4 6.4 17.1 9.5 14.2 7.5 31-1 45.5-7.7a201.8 201.8 0 0 1 124-14.6c-1.8 3 2.2 6.5 5.5 5.8s5.6-3.6 7.8-6.2c12-13.7 29.9-20.5 47.3-25.6 40.2-11.9 83.7-18 123.8-6a99.2 99.2 0 0 1 47.2 28.7c4.8 5.7 9 12.2 15.7 15.5 12.2 6.1 28.4-.9 39.7 6.7 5 3.3 8 9 12.2 13.3 18.4 19.7 50.5 10.6 77.4 12.7 31.9 2.4 58.7 22.1 86.3 39.3z" fill="url(#b)"/><path d="M465 202.4V4.2h-70L278.4 196.7v54.5H404v68.3h61v-68.3h36v-48.8zM404 65.7v136.7h-79.2z" fill="url(#a)"/><path d="M724.2 42.7Q699.8 0 639.2 0t-85 42.7q-24.4 42.6-24.4 121.2a388.6 388.6 0 0 0 3.5 54q5.7 40.5 21 67a81 81 0 0 0 16.6 20.6q24.9 21.8 68.4 21.8 49.5 0 74.9-28.3a83.6 83.6 0 0 0 10-14.1q19.3-33.5 23.4-89.5 1.1-15 1-31.5 0-78.6-24.4-121.2zM602.5 79q9-27.6 36.7-27.6T675.7 79q8.6 27.6 8.6 84.9 0 17.4-.9 32.2-1.8 31.7-7.7 51.5-8.7 29-36.5 29t-36.7-29q-4.6-14.8-6.9-36.4a461.3 461.3 0 0 1-2.1-47.3q0-57.3 9-84.9z" fill="url(#c)"/><path d="M963.5 202.4V4.2h-70l-107.3 177-9.3 15.5v54.5h125.6v68.3h61v-68.3h35.9v-48.8zm-140.2 0l20.3-35 58.9-101.7v136.7z" fill="url(#d)"/><path d="M1365.7 517.9l-.3 121.9h-177c-3-7.4-6-9.4-11.8-14.7a57.7 57.7 0 0 0-23.2-11.2c-50.7-14.9-107.7-19.8-154-42a150 150 0 0 1-46.1-32.8c-28.2-29.8-50.3-77.1-91.3-75-10 .4-19.4 4.2-29 6.4a103.6 103.6 0 0 1-82.4-16c-13.7-9.8-25.2-23-40.4-30-13.6-6.3-29-7.1-44.1-7.6-40.4-1.3-81.6-1.2-122.4-2.9-74.3-3-147.3-12.1-211.7-47.5-13.7-7.5-27-16.2-41.8-21a171 171 0 0 0-50.7-5.6l-98-1.2c-11-.1-22.8-.4-32.6-5.6-10.7-5.8-17.6-16.5-24-26.7-11.4-18-23-36.4-39.7-49.8A73.3 73.3 0 0 0 0 239.1v-56a301.3 301.3 0 0 0 113.8 13.2c7.6-.6 15.6-1.3 22.4 2.1 11.5 5.9 14.4 21 22.9 31 11.5 13.4 31.5 15 49.3 15.4l71 2 43.7 1.3c16.1.5 33.6.5 46.4-9.2 7-5.4 13.8-14 22.5-12.6 9 1.4 12.6 12 18.1 19a33.4 33.4 0 0 0 9.3 8.3c11.3 7.1 26.3 9 39.8 11.8l6.9 1.7a153 153 0 0 1 77.8 50.1 165 165 0 0 0 28-6.8A167 167 0 0 0 611 291c5.4 15 14.1 32.8 30 33.6 25 1.3 43.6-40.5 65-27.7 3.3 2 6 5 9.1 7a12 12 0 0 0 3.5 1.4c6.2 1.5 12.1-3.3 16-8.3 16-20.4 23-53.5 43.3-64.3a30.2 30.2 0 0 1 12.7-3.5c17.8-1 30.5 13.3 43.5 27a153.8 153.8 0 0 0 12.9 12.3c16 13.3 36.2 18.8 56.4 24.6 16.7 4.9 33.4 10 47.4 19.9a143 143 0 0 1 13.7 11.3c12.9 11.8 25.2 24.5 42 26.9 18.6 2.6 40.6-7.9 54.5 4.5 7.6 6.7 9.3 17.7 13.6 26.9 15.5 33.7 60.2 38.7 93.6 55 14.1 6.9 27.4 16.7 43 19.3z" fill="url(#e)"/><path d="M1188.7 639.8H0V234.2c16.1 0 32.5 7 45.2 17.4 16.6 13.4 28.3 31.8 39.6 49.8 6.5 10.2 13.4 21 24.1 26.7 9.8 5.2 21.5 5.4 32.6 5.6l98 1.2c17 .2 34.4.4 50.7 5.7 14.9 4.7 28.1 13.4 41.8 20.9 64.4 35.4 137.4 44.5 211.8 47.5 40.8 1.7 82 1.5 122.3 2.9 15 .5 30.5 1.3 44 7.6 15.3 7 26.8 20.2 40.5 30a103.6 103.6 0 0 0 82.3 16c9.7-2.3 19.2-6 29.2-6.5 41-2 63 45.3 91.1 75.1a152 152 0 0 0 46.2 32.8c46.3 22.1 103.3 27 154 42a57.7 57.7 0 0 1 23.1 11.2 51.5 51.5 0 0 1 12.2 19.7z" fill="url(#f)"/></svg>

screen shot 2018-05-15 at 8 57 13 am

it renders this:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1365.7 639.8" class="injected-svg" style="width:100%;pointer-events:none" data-src="/static/media/404.4d32f49b.svg"><defs><linearGradient id="b-15" x1="430.8" y1="197.7" x2="1480.8" y2="376.3" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#aaa9b2"></stop><stop offset="1" stop-color="#90919c"></stop></linearGradient><linearGradient id="a-15" x1="159.6" y1="44.4" x2="1094.1" y2="443.5" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#4adec2"></stop><stop offset="1" stop-color="#007cc3"></stop></linearGradient><linearGradient id="c-15" x1="190.4" y1="-27.9" x2="1125" y2="371.1" xlink:href="#a"></linearGradient><linearGradient id="d-15" x1="236.4" y1="-135.6" x2="1170.9" y2="263.4" xlink:href="#a"></linearGradient><linearGradient id="e-15" y1="411.5" x2="1365.7" y2="411.5" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#534e55"></stop><stop offset="1" stop-color="#413f4a"></stop></linearGradient><linearGradient id="f-15" y1="437" x2="1188.7" y2="437" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#363032"></stop><stop offset="1" stop-color="#1b1718"></stop></linearGradient></defs><path d="M1365.7 262.6v258.3L1211.2 460c-15.6-2.6-28.8-12.4-43-19.3-33.4-16.3-78-21.3-93.6-55-4.3-9.2-6-20.1-13.6-26.8-14-12.4-36-2-54.4-4.6-22.7-3.2-37.1-25-55.8-38.2-31-21.9-74.6-20.2-103.8-44.4-18.3-15.1-32.8-40.8-56.4-39.5-30.7 1.8-37.1 43.7-56 67.9-4 5-9.9 9.7-16 8.3-5-1.1-8.2-5.8-12.6-8.4-21.5-12.8-40 29-65 27.7-16-.8-24.6-18.5-30-33.6a166.8 166.8 0 0 1-67.2 26.3 153 153 0 0 0-84.6-51.8c-13.5-3-28.6-4.7-39.8-11.9a73.2 73.2 0 0 1 42.4-17c8.4-.2 16.7 1.4 25 1.1 24.3-.8 45.2-17.5 69.1-21.7 15.1-2.6 30.6-.2 45.9.4a190.5 190.5 0 0 0 99-23.4c4.8-2.6 10-5.6 15.4-4.9 6.6.8 11.4 6.4 17.1 9.5 14.2 7.5 31-1 45.5-7.7a201.8 201.8 0 0 1 124-14.6c-1.8 3 2.2 6.5 5.5 5.8s5.6-3.6 7.8-6.2c12-13.7 29.9-20.5 47.3-25.6 40.2-11.9 83.7-18 123.8-6a99.2 99.2 0 0 1 47.2 28.7c4.8 5.7 9 12.2 15.7 15.5 12.2 6.1 28.4-.9 39.7 6.7 5 3.3 8 9 12.2 13.3 18.4 19.7 50.5 10.6 77.4 12.7 31.9 2.4 58.7 22.1 86.3 39.3z" fill="url(#b-15)"></path><path d="M465 202.4V4.2h-70L278.4 196.7v54.5H404v68.3h61v-68.3h36v-48.8zM404 65.7v136.7h-79.2z" fill="url(#a-15)"></path><path d="M724.2 42.7Q699.8 0 639.2 0t-85 42.7q-24.4 42.6-24.4 121.2a388.6 388.6 0 0 0 3.5 54q5.7 40.5 21 67a81 81 0 0 0 16.6 20.6q24.9 21.8 68.4 21.8 49.5 0 74.9-28.3a83.6 83.6 0 0 0 10-14.1q19.3-33.5 23.4-89.5 1.1-15 1-31.5 0-78.6-24.4-121.2zM602.5 79q9-27.6 36.7-27.6T675.7 79q8.6 27.6 8.6 84.9 0 17.4-.9 32.2-1.8 31.7-7.7 51.5-8.7 29-36.5 29t-36.7-29q-4.6-14.8-6.9-36.4a461.3 461.3 0 0 1-2.1-47.3q0-57.3 9-84.9z" fill="url(#c-15)"></path><path d="M963.5 202.4V4.2h-70l-107.3 177-9.3 15.5v54.5h125.6v68.3h61v-68.3h35.9v-48.8zm-140.2 0l20.3-35 58.9-101.7v136.7z" fill="url(#d-15)"></path><path d="M1365.7 517.9l-.3 121.9h-177c-3-7.4-6-9.4-11.8-14.7a57.7 57.7 0 0 0-23.2-11.2c-50.7-14.9-107.7-19.8-154-42a150 150 0 0 1-46.1-32.8c-28.2-29.8-50.3-77.1-91.3-75-10 .4-19.4 4.2-29 6.4a103.6 103.6 0 0 1-82.4-16c-13.7-9.8-25.2-23-40.4-30-13.6-6.3-29-7.1-44.1-7.6-40.4-1.3-81.6-1.2-122.4-2.9-74.3-3-147.3-12.1-211.7-47.5-13.7-7.5-27-16.2-41.8-21a171 171 0 0 0-50.7-5.6l-98-1.2c-11-.1-22.8-.4-32.6-5.6-10.7-5.8-17.6-16.5-24-26.7-11.4-18-23-36.4-39.7-49.8A73.3 73.3 0 0 0 0 239.1v-56a301.3 301.3 0 0 0 113.8 13.2c7.6-.6 15.6-1.3 22.4 2.1 11.5 5.9 14.4 21 22.9 31 11.5 13.4 31.5 15 49.3 15.4l71 2 43.7 1.3c16.1.5 33.6.5 46.4-9.2 7-5.4 13.8-14 22.5-12.6 9 1.4 12.6 12 18.1 19a33.4 33.4 0 0 0 9.3 8.3c11.3 7.1 26.3 9 39.8 11.8l6.9 1.7a153 153 0 0 1 77.8 50.1 165 165 0 0 0 28-6.8A167 167 0 0 0 611 291c5.4 15 14.1 32.8 30 33.6 25 1.3 43.6-40.5 65-27.7 3.3 2 6 5 9.1 7a12 12 0 0 0 3.5 1.4c6.2 1.5 12.1-3.3 16-8.3 16-20.4 23-53.5 43.3-64.3a30.2 30.2 0 0 1 12.7-3.5c17.8-1 30.5 13.3 43.5 27a153.8 153.8 0 0 0 12.9 12.3c16 13.3 36.2 18.8 56.4 24.6 16.7 4.9 33.4 10 47.4 19.9a143 143 0 0 1 13.7 11.3c12.9 11.8 25.2 24.5 42 26.9 18.6 2.6 40.6-7.9 54.5 4.5 7.6 6.7 9.3 17.7 13.6 26.9 15.5 33.7 60.2 38.7 93.6 55 14.1 6.9 27.4 16.7 43 19.3z" fill="url(#e-15)"></path><path d="M1188.7 639.8H0V234.2c16.1 0 32.5 7 45.2 17.4 16.6 13.4 28.3 31.8 39.6 49.8 6.5 10.2 13.4 21 24.1 26.7 9.8 5.2 21.5 5.4 32.6 5.6l98 1.2c17 .2 34.4.4 50.7 5.7 14.9 4.7 28.1 13.4 41.8 20.9 64.4 35.4 137.4 44.5 211.8 47.5 40.8 1.7 82 1.5 122.3 2.9 15 .5 30.5 1.3 44 7.6 15.3 7 26.8 20.2 40.5 30a103.6 103.6 0 0 0 82.3 16c9.7-2.3 19.2-6 29.2-6.5 41-2 63 45.3 91.1 75.1a152 152 0 0 0 46.2 32.8c46.3 22.1 103.3 27 154 42a57.7 57.7 0 0 1 23.1 11.2 51.5 51.5 0 0 1 12.2 19.7z" fill="url(#f-15)"></path></svg>

screen shot 2018-05-15 at 8 57 19 am

Do you have any guess why this is happening and why when it is rendered the URL's are being adjusted? When I test simply copying the SVG code into the Chrome instpector html it renders on the page fine.

How to use react-svg for images used in CSS background?

I am using few svg image icons as a background image and on hover it should change to different color. Right now I am using hover image for hover effect which is little bit slow to load on mouseover and not very smooth looks jerky. I am looking for a way if I could use svg fill property in css to change the svg color on hover rather having hover image.

Implementing a fallback with react-svg

I am going to be using your package in an app I'm working on and need a way to implement a fallback to a .png image if there is an error or compatibility issue with the SVG file. Can you recommend a way to do this using your package? Is there an onError or fallback prop available? Thanks for your work.

clickable in any part of svg

hi
i have some svg file like map ,i want to click on any part and see id of any part in console
is this package can solve this?

ID's in SVG's

I am attempting to modify certain polygons within the svg through document.getElementById() and calling out the specific ID I have set in my svg file. However, I see that upon inspecting source in the browser, the injection loses the ID. Reading some other issues, it sounds like this is intentional so multiple instances of an SVG can be added. Is there a workaround for when I still need to access polygons with ID?

Two div elements wrap svg icon

Is it necessary to wrap SVG by 2 div elements in DOM? Maybe render only svg without div's or use only one wrapper element?

component re-rendered

Whenever my state is changed, my react-svg component will be re-rendered. Do you have this situation?

Correct way to include in app?

The documentation says to import ReactSVG by doing this import ReactSVG from '../src/index.js';

but that doesn't seem right.

I am missing something?

Rendering fails since 4.0.3

Last working version for me seems to be 4.0.2. Versions after that give me following error when visiting the page. Compiling itself seems to work without issues.

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

npm -v: 6.1.0
node -v: v8.11.2

replaceChild svg unable to render

I am working with an electron app that is utilizing the react framework and ran into an issue with svg not rendering. This seems to happen when I filter a list or change the sequence of a list...

From react code I am setting a new array to maintain the immutability aspect but something seems to throw off react-svg.

Starting State
sample1

Update State (new array) - When a 'reminder' is selected it hands the call to the parents method that utilizes .map() to find, update and return a new array that gets used on this.setState().
sample2

Here is the error:
C:\MHS-Portal\node_modules\react-svg\lib\index.js:537 Uncaught TypeError: Cannot read property 'replaceChild' of null

Occurs in the react-svg\lib\index.js

// Replace the image with the svg
el.parentNode.replaceChild(svg, el);

Since the parentNode appears null, it will leave the image tag in markup. Since it uses data-src it also prevents it from displaying...if I change to simply src it still loads.

<img class="reminder--icon " data-src="../media/Circle_Check.svg">

Since I am only using electron that targets only Chromium is it possible to not have to worry about any of the fallback logic and just render svg from the start? I am new to React so it could be I am utilizing something improperly there as well too.

react-svg android compatibility

When I build react-svg for android , it throws error. Do we have any alternative for android? Please help My code is below

import ReactSVG from 'react-svg';

Click Support

Love the library, it's saving us a lot of time and effort. Is there any chance you're planning to add onClick support? Often we use svgs like buttons, and it would be great if the component could pass whatever function it received from props onto a click handler of the first div. I could create a pull request if you want!

Dynamic class names

I am trying to add a class to the ReactSVG component once something happens. I am using the latest version of react, react-svg, classnames.

render() {
    const themeIcon = className( "qilin-icon", {
        "is-active" : this.props.isThemeToggled,
    } );

    return (
        <ReactSVG className={themeIcon} path="images/icons/menu/theme.svg" />
    );
}

themeIcon is a valid string:

zrzut ekranu 2016-09-26 o 23 17 00

CSS clases are not changing in the DOM once SVG is loaded:

zrzut ekranu 2016-09-26 o 23 18 18

Is there an easy way to dynamically change SVG classes or should I use refs and the callback function?

'window is not defined' error when importing

Why am I getting an error

node_modules/svg-injector/svg-injector.js:464 }(window, document)); ^ ReferenceError: window is not defined

I just installed and imported
import ReactSVG from 'react-svg';

Throws me the error.

does not apear SVG

In my react project, I use this library to show SVG.

However, my SVG does not appear.

Can anyone give me some advice?

2018-08-15 18 26 23

2018-08-15 18 27 19

Unable to load the image

import React from "react"
import ReactSVG from 'react-svg'
class Integrat extends React.Component {
render() {

    return  <div>
        <ReactSVG path="icon.svg"></ReactSVG>
      
    </div>
}

}
export default Integrat

My svg file is in the same folder ,
i tried giving path as "./icon.svg", it didnt load

ingect-element error in 4.1.1

After updating from 4.0.17 to 4.1.1 I started seeing this error.

inject-element.js:208 Uncaught TypeError: callback is not a function
    at Array.<anonymous> (inject-element.js:208)
    at request-queue.js:15

Img Default Special Border

So the svg file I loaded is working great. This is more of a small aesthetic/experience issue. I have added the ReactSVG component to one of my pages. However, when the page loads there is a slight blink of a white rectangular border (the page background is black) and then my svg appears and the border disappears. I think this issue has something to do with the fact that the default element, when ReactSVG is mounted, is an img element with no src, and that happens to be an image with a special white border that can't be removed with css. Is there a way to fix this?

UPDATE
I selected the img separately and set the display:none. I'm curious is there a reason for the default img element?

Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

I have this warning when running react-svg from create-react-app boilterplate.

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

Could you consider replacing this by below in src/index.js?
import React, { Component, PropTypes } from 'react'

to

import React, { Component } from 'react'
import PropTypes from 'prop-types'

Thanks in advance

CSS Height issue, parent of svg

Hi, I interested with your repo. But something happen. when I declare the reactSVG like this
<ReactSVG path={LogoBanner} alt="" svgStyle={{ width:"100%", height:"auto" }} />

that will create div parent with svg tag inside. But the problem is the div parent is different height with the svg tag (the div is more tall then the svg), I inspect and not found which one makes the parent taller

This is what I wanted!

This is awesome!
It can more easily handle SVG !

May I use sprite SVG someday?

Thank U

Changing ids of gradients in defs

I've been having issues where it's changing the ID of my gradient and therefore breaking the reference to the style, and because the appending number is a global variable, it changes each time I load a page.

It's possible to stop incrementing the ids by removing linearGradient: ['fill', 'stroke'], from src/inject-element.js in the svg-injector module, but can you set it so that each of these items in the iriElementsAndProperties object can be turned on and off in a config? If we're writing our code properly, we shouldn't get duplicate ids anyway

Easy way to change fill?

It seems like this doesn't work to change fill:
<ReactSVG path={ StackIcon } svgStyle={ { width: 16, fill: '#363636' } }/>

Is there something i'm missing? Or is there a different way to change the fill?

Getting an error with Jest tests

Trying to write some tests on a component with children that use react-svg, but running into the following error:

console.error node_modules\react-dom\cjs\react-dom.development.js:14113
      The above error occurred in the <ReactSVG> component: 
      ...

ReferenceError: SVGSVGElement is not defined

Any thoughts?

SVG Injector No Longer Maintained

Not really an issue, but more of a question.

This library heavily relies on the SVGInjector library as a dependency. There are open PR's in the SVGInjector repo dating back to over 2 years ago, aka it seems to no longer be maintained.

@tanem and any other contributors to react-svg, do you foresee this being an issue?

For instance, I want to be able to provide an onClick attribute, but svg-injector strips out these attributes. I'm wondering what the maintainers of react-svg think about this situation. Thanks

Problem with IE9-Win7

The react component didn't work for me on IE9-Win7 (using this vagrant machine https://github.com/markhuber/modern-ie-vagrant/blob/master/Vagrantfile).

The XDomainRequest in iconic/SVGInjector kept getting 'aborted'. If I attached the onerror handler, I had an error.
Of course, IE9 does not give you an actual error message... (https://developer.mozilla.org/en-US/docs/Web/API/XDomainRequest/onerror):

Note: There is no way to determine the cause of the error from the XDomainRequest interface.

Then, I thought it might be caused by the fact that the XMLDomainRequest implementation in SVGInjector was missing the onprogress, which can cause the abort (http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9):

I'm not sure this is the same problem, but in my case all of these needed to be set: onerror; onprogress; ontimeout; and onload. Here are some references that discuss the problem:

http://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified
http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/
http://rudovsky.blogspot.com/2012/09/microsoft-shit-xdomainrequest.html
faye/faye#98
There are many others as well. They're scattered and sometimes contradictory in their suggested solution. For example, one suggests wrapping the xdr.send call in a setTimeout.

Still had the problem, so I thought it might be caused by the fact that it's an image (http://stackoverflow.com/questions/16966758/can-xdomainrequest-be-used-to-load-and-draw-images):

Complications of Downloading images with XDomainRequest in IE

IE only allows XdomainRequest to work with plain-text data (ARGH!!): > http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

IE will also sniff all incoming data using its FindMimeFromData. So even if you strip off the url's type prefix (data:image/png;base64), this sniffer will realize that your base64 text is really an image and treat it accordingly: http://msdn.microsoft.com/en-us/library/ms775147(v=vs.85).aspx

A possible try would be to re-encode the base64 text somehow to confuse the sniffer.

MS apparently realizes that their CORS policy is too restrictive and is planning on adding expanded CORS support to their webAPI: http://channel9.msdn.com/Shows/Web+Camps+TV/ASPNET-Web-API-and-CORS-Support

Otherwise you’re left with the current solution of bouncing images off your own web server so that they’re not X-domain anymore.

But the fix was much more simple, I just used the latest version of SVGInjector (1.1.3).

TL; DR: use [email protected] to fix this issue.

I'm not doing a PR because I changed the way svg-injector is required (I put it as a module in package.json), whereas you have as a lib.

Double Div

Is there a reason this is output Div > Div > SVG? It could be just Div > SVG right?

svgs don't get loaded

I've set up the react-svg last night and it worked correctly. Today I'm running the server and the SVGs don't get displayed, but they still get console logged. Any ideas of why that might be happening?

Cannot read property 'DOMNodeInsertedByJs' of undefined

Hi,

I'm getting this error a fair amount in production, specifically on Chrome Mobile from Android 6.0 and 7.1 devices: "Cannot read property 'DOMNodeInsertedByJs' of undefined", happening right here: https://github.com/atomic-app/react-svg/blob/master/src/index.js#L47, after this call: https://github.com/atomic-app/react-svg/blob/master/src/index.js#L66

Here's the full stacktrace:

TypeError Uncaught TypeError: Cannot read property 'DOMNodeInsertedByJs' of undefined 
    <anonymous>:1:6816 HTMLDocument.DOMNodeInsertedFunc
    webpack:///~/react-svg/lib/index.js:76 e.u.value
    webpack:///~/react-svg/lib/index.js:92 e.u.value
    webpack:///~/react-dom/lib/ReactCompositeComponent.js:614 w.updateComponent
    webpack:///~/react-dom/lib/ReactCompositeComponent.js:547 w.receiveComponent
    webpack:///~/react-dom/lib/ReactReconciler.js:125 Object.i.receiveComponent
    webpack:///~/react-dom/lib/ReactChildReconciler.js:109 Object.c.updateChildren
    webpack:///~/react-dom/lib/ReactMultiChild.js:213 h.v.Mixin._reconcilerUpdateChildren
    webpack:///~/react-dom/lib/ReactMultiChild.js:312 h.v.Mixin._updateChildren

I assume it has to do with some specifics around Chrome Mobile element insertion -- would it be save to just guard against this.container being falsy in the same way we do with removeSVG, assuming that componentWillReceiveProps will successfully call it subsequently?

Unable to load SVG file: {path}

I have installed react-svg and I am trying to import an svg image. Here is my file:

import React, {PropTypes} from 'react';
import styles from '../common/contentBoxStyles';
import ReactSVG from 'react-svg';

const WeatherReport = ({report}) => {
  return (
  	<div style={styles.body} className="row">
  		<div style={styles.weatherBoxContainer}>
  			<div className="col-sm-2 col-md-offset-1" style={styles.weatherBoxContainer.weatherCard}>
  				<div style={styles.weatherBoxContainer.weatherReport}>
  					<ReactSVG path={'../common/svg/O1n.svg'} callback={(svg) => console.log(svg)} />
  					<div className="row" style={styles.weatherBoxContainer.temps}>
  						<div className="col-sm-4">
  							<div>{Math.floor(report.main.temp_max)}°</div>
  							<div>{Math.floor(report.main.temp_min)}°</div>
  						</div>
  						<div className="col-sm-8" style={styles.weatherBoxContainer.currentTemp}>
  							{Math.floor(report.main.temp)}°
  						</div>
  					</div>
  				</div>
  				CA
  			</div>
  			<div className="col-sm-2" style={styles.weatherBoxContainer.weatherCard}>
  				<div style={styles.weatherBoxContainer.weatherReport}>
  					Report
  				</div>
  				UT
  			</div>
  			<div className="col-sm-2" style={styles.weatherBoxContainer.weatherCard}>
  				<div style={styles.weatherBoxContainer.weatherReport}>
  					Report
  				</div>
  				MN
  			</div>
  			<div className="col-sm-2" style={styles.weatherBoxContainer.weatherCard}>
  				<div style={styles.weatherBoxContainer.weatherReport}>
  					Report
  				</div>
  				DC
  			</div>
  			<div className="col-sm-2" style={styles.weatherBoxContainer.weatherCard}>
  				<div style={styles.weatherBoxContainer.weatherReport}>
  					Report
  				</div>
  				NY
  			</div>
  		</div>
  	</div>
  );
};

WeatherReport.propTypes = {
  report: PropTypes.object
};

export default WeatherReport;

Here is my file structure:

src
|_ _components
|    |_ _dashboard
|    |    |_ _WeatherReport.js
|    |_ _common
|         |_ _svg
|              |_ _O1n.svg

Console reads out:
Unable to load SVG file: ../common/svg/O1n.svg
undefined

I have installed through npm w/o issues:
svg-injector
react-svg

What am I missing here?

IE11 Support

First of all thanks for this library, I have been using it a lot in a number of production projects.

Have you done much work with this library on IE11. I have a project where on all other browsers layout works correctly but on IE11 the height of the SVG doesn't adjust when the width is changed. It looks like possibly adding preserveAspectRatio="xMinYMin" seemed to help but I don't know how to pass that down to the SVG with this library.

[Feature Request] - Add API prop to prefix style declarations exported by Adobe Illustrator

Really digging react-svg! However, I've run into a problem which requires a manual process to correct. When a designer hands over svgs exported from Adobe Illustrator - the generated styles have matching selectors - which causes colors to "spill over" into other svgs. If this component had an api option that steps through and prepends these styles with the something like the svg filename or even a custom string that would be awesome. Right now I have to manually adjust each svg so the styles dont clash and recolor other svgs. I'm sure many users would benefit from this feature.

image

v3 version not compatible with styled-component

hi there ~

currently i am using v2 version for my project, and it works fine:
image

after upgrade to v3:
image

project usage example:

import styled from 'styled-components'
import ReactSVG from 'react-svg'
... 
const FilterIcon = styled(ReactSVG)`
  fill: ${theme('font')};
  width: 16px;
  height: 16px;
  margin-top: 2px;
  margin-left: 3px;
`
... 

<FilterIcon path={`${ICON_ASSETS}/cmd/filter.svg`} />

it seems v3 change: className -> svgClassName cause the issue

svg is invisible

Hey! I guess i am gonna need some help. I am trying to render an SVG, but it's not appearing.

Here's my snippet:

import { render } from 'react-dom'
import ReactSVG from 'react-svg'
import PlayButton from './fonts/player/play.svg';

class ControlBtn extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return(
            <ReactSVG
            path={PlayButton}
            evalScripts="always"
            onInjected={svg => {
                console.log('onInjected', svg)
            }}
            renumerateIRIElements={false}
            svgClassName="svg-class-name"
            svgStyle={{ width: 200, height: 200 }}
            className="wrapper-class-name"
            onClick={() => {
                console.log('wrapper onClick')
            }}
            />
        );
    }
}

export { ControlBtn };```

in the DOM, i got the following: 

`<div class="wrapper-class-name"><div><div class="svg-class-name" data-src="data:image/svg+xml;base64,.............=" style="width:200px;height:200px"></div></div></div>`

I am using in on electronjs with React. 

Any help would be appreciated here! Thanks! 

deprecated source

Hello. Nice library 👍

I just recognized one thing. Tried to find the source or documentation npm docs react-svg and the browser shows me this repository. Tried className and svgClassName as documented but didn't reach the goal 😞

After quick look into node_modules I find that your have upgraded npm exclude github repository.

For example: wrapperClassName, and updated role of className?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.