React Inlinesvg

4.3.0 · active · verified Sun Apr 19

react-inlinesvg is a React component and hook designed for loading and rendering SVG files directly inline within your application's DOM. It supports various `src` inputs including local paths, remote URLs, data URIs, and raw SVG strings, offering broad flexibility. The current stable version is 4.3.0. The package maintains an active release cadence, frequently publishing minor updates for bug fixes, dependency upgrades, and new features, such as the `useInlineSVG` hook introduced in v4.3.0. Key differentiators include robust caching mechanisms for remote SVGs (both in-memory and browser cache with `CacheProvider`), server-side rendering (SSR) compatibility, and extensive customization through props like `preProcessor` for SVG content manipulation, `loader` for loading states, and comprehensive error handling callbacks. This enables developers to dynamically style and interact with SVGs, addressing common challenges like external stylesheet coupling and inefficient image requests.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `SVG` component and `useInlineSVG` hook to load and display SVGs, including remote and local files, with loading indicators, error handling, caching via `CacheProvider`, and pre-processing for dynamic styling.

import React, { useState } from 'react';
import SVG from 'react-inlinesvg';
import CacheProvider from 'react-inlinesvg/provider';

const MySVGIcon = ({ src, title, description, width = 64, height = 64 }) => {
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  return (
    <SVG
      src={src}
      width={width}
      height={height}
      title={title}
      description={description}
      cacheRequests={true}
      loader={loading && <div style={{ width, height, background: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Loading...</div>}
      onError={(err) => {
        console.error('SVG loading error:', err);
        setError(err);
        setLoading(false);
      }}
      onLoad={(loadedSrc, isCached) => {
        console.log(`SVG loaded: ${loadedSrc} (cached: ${isCached})`);
        setLoading(false);
        setError(null);
      }}
      preProcessor={(code) => code.replace(/fill="(?!none).*?"/g, 'fill="currentColor"')}
      // Any additional props are passed to the SVG element
      style={{ color: '#007bff' }} // Example: Change SVG fill via currentColor
    >
      {error ? <div style={{ width, height, border: '1px solid red', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'red' }}>Error loading SVG</div> : null}
    </SVG>
  );
};

export default function App() {
  const remoteSvgSrc = 'https://cdn.svglogos.dev/logos/react.svg';
  const localSvgPath = '/my-local-icon.svg'; // Ensure this file exists in your public directory

  // In a real app, ensure your build system handles local SVG paths appropriately
  // For CRA, localSvgPath can be a direct path to public/, or import from assets folder.
  // For illustration purposes, assuming it's accessible.

  return (
    <CacheProvider>
      <div style={{ fontFamily: 'sans-serif', padding: '20px' }}>
        <h1>react-inlinesvg Demo</h1>
        <p>Remote SVG (React logo):</p>
        <MySVGIcon src={remoteSvgSrc} title="React Logo" width={80} height="auto" />
        
        <p style={{ marginTop: '20px' }}>Example of a missing local SVG (will show error fallback):</p>
        <MySVGIcon src={localSvgPath} title="Local Icon" width={50} height={50} />

        <p style={{ marginTop: '20px' }}>Using useInlineSVG hook (from v4.3.0):</p>
        <InlineSVGHookDemo />
      </div>
    </CacheProvider>
  );
}

// Example using the useInlineSVG hook
function InlineSVGHookDemo() {
  const { SVG: SvgElement, loading, error } = useInlineSVG('https://cdn.svglogos.dev/logos/typescript.svg');

  if (loading) return <div style={{ width: 80, height: 80, background: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Hook Loading...</div>;
  if (error) return <div style={{ width: 80, height: 80, border: '1px solid red', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'red' }}>Hook Error: {error.message}</div>;
  
  return SvgElement ? <SvgElement title="TypeScript Logo" width={80} height={80} style={{ color: '#007ACC' }} /> : null;
}

view raw JSON →