React SVG Component

17.2.4 · active · verified Sun Apr 19

react-svg is a React component designed to fetch SVG files from a given URL and inject their raw markup directly into the DOM, rather than rendering them as `<img>` tags. This approach, powered by the underlying `@tanem/svg-injector` library, enables full manipulation of the SVG's internal elements via CSS and JavaScript, unlocking possibilities like dynamic styling, animation, and interactivity that are not possible with traditional `<img>` elements. It also features client-side caching of fetched SVGs to reduce redundant network requests for repeated assets. The package is actively maintained, with its current stable version being 17.2.4, and exhibits a healthy release cadence, often seeing updates within a three-month window. It ships with TypeScript type definitions, enhancing development in TypeScript environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `ReactSVG` to load an external SVG, including lifecycle callbacks, error handling, and a loading fallback. It highlights DOM manipulation before injection.

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

const rootElement = document.getElementById('root');

if (rootElement) {
  const root = createRoot(rootElement);
  root.render(
    <div>
      <h1>My Application</h1>
      <p>Loading an external SVG using ReactSVG:</p>
      <ReactSVG
        src="/path/to/your/image.svg"
        beforeInjection={(svg) => {
          console.log('SVG about to be injected:', svg.id);
          svg.setAttribute('style', 'width: 100px; height: 100px;');
        }}
        afterInjection={(svg) => console.log('SVG injected:', svg.id)}
        onError={(error) => console.error('Error loading SVG:', error.message)}
        loading={() => <span style={{ color: 'blue' }}>Loading SVG...</span>}
        fallback={() => <span style={{ color: 'red' }}>Could not load SVG</span>}
      />
      <p>Ensure 'image.svg' is accessible at the specified path.</p>
    </div>
  );
} else {
  console.error("Root element 'root' not found.");
}

view raw JSON →