{"id":11727,"library":"react-inlinesvg","title":"React Inlinesvg","description":"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.","status":"active","version":"4.3.0","language":"javascript","source_language":"en","source_url":"git://github.com/gilbarbara/react-inlinesvg","tags":["javascript","react","svg","typescript"],"install":[{"cmd":"npm install react-inlinesvg","lang":"bash","label":"npm"},{"cmd":"yarn add react-inlinesvg","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-inlinesvg","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core React library required for component and hook functionality, listed as a peer dependency.","package":"react","optional":false}],"imports":[{"note":"The primary component for inline SVG rendering. While CommonJS `require` might work in some transpiled environments, native ESM `import` is the recommended and modern approach for React applications.","wrong":"const SVG = require('react-inlinesvg');","symbol":"SVG","correct":"import SVG from 'react-inlinesvg';"},{"note":"Introduced in v4.3.0, this hook provides programmatic access to the SVG loading lifecycle. It's a named export.","symbol":"useInlineSVG","correct":"import { useInlineSVG } from 'react-inlinesvg';"},{"note":"Used to enable persistent browser caching for SVGs. This is a default export from a subpath, not a named export from the main package.","wrong":"import { CacheProvider } from 'react-inlinesvg';","symbol":"CacheProvider","correct":"import CacheProvider from 'react-inlinesvg/provider';"}],"quickstart":{"code":"import React, { useState } from 'react';\nimport SVG from 'react-inlinesvg';\nimport CacheProvider from 'react-inlinesvg/provider';\n\nconst MySVGIcon = ({ src, title, description, width = 64, height = 64 }) => {\n  const [error, setError] = useState(null);\n  const [loading, setLoading] = useState(true);\n\n  return (\n    <SVG\n      src={src}\n      width={width}\n      height={height}\n      title={title}\n      description={description}\n      cacheRequests={true}\n      loader={loading && <div style={{ width, height, background: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Loading...</div>}\n      onError={(err) => {\n        console.error('SVG loading error:', err);\n        setError(err);\n        setLoading(false);\n      }}\n      onLoad={(loadedSrc, isCached) => {\n        console.log(`SVG loaded: ${loadedSrc} (cached: ${isCached})`);\n        setLoading(false);\n        setError(null);\n      }}\n      preProcessor={(code) => code.replace(/fill=\"(?!none).*?\"/g, 'fill=\"currentColor\"')}\n      // Any additional props are passed to the SVG element\n      style={{ color: '#007bff' }} // Example: Change SVG fill via currentColor\n    >\n      {error ? <div style={{ width, height, border: '1px solid red', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'red' }}>Error loading SVG</div> : null}\n    </SVG>\n  );\n};\n\nexport default function App() {\n  const remoteSvgSrc = 'https://cdn.svglogos.dev/logos/react.svg';\n  const localSvgPath = '/my-local-icon.svg'; // Ensure this file exists in your public directory\n\n  // In a real app, ensure your build system handles local SVG paths appropriately\n  // For CRA, localSvgPath can be a direct path to public/, or import from assets folder.\n  // For illustration purposes, assuming it's accessible.\n\n  return (\n    <CacheProvider>\n      <div style={{ fontFamily: 'sans-serif', padding: '20px' }}>\n        <h1>react-inlinesvg Demo</h1>\n        <p>Remote SVG (React logo):</p>\n        <MySVGIcon src={remoteSvgSrc} title=\"React Logo\" width={80} height=\"auto\" />\n        \n        <p style={{ marginTop: '20px' }}>Example of a missing local SVG (will show error fallback):</p>\n        <MySVGIcon src={localSvgPath} title=\"Local Icon\" width={50} height={50} />\n\n        <p style={{ marginTop: '20px' }}>Using useInlineSVG hook (from v4.3.0):</p>\n        <InlineSVGHookDemo />\n      </div>\n    </CacheProvider>\n  );\n}\n\n// Example using the useInlineSVG hook\nfunction InlineSVGHookDemo() {\n  const { SVG: SvgElement, loading, error } = useInlineSVG('https://cdn.svglogos.dev/logos/typescript.svg');\n\n  if (loading) return <div style={{ width: 80, height: 80, background: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Hook Loading...</div>;\n  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>;\n  \n  return SvgElement ? <SvgElement title=\"TypeScript Logo\" width={80} height={80} style={{ color: '#007ACC' }} /> : null;\n}","lang":"typescript","description":"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."},"warnings":[{"fix":"Replace `innerRef={myRef}` with `ref={myRef}`.","message":"The `innerRef` prop on the `SVG` component was renamed to `ref` (standard React ref prop) in version 4.2.0. Direct usage of `innerRef` will no longer work as expected.","severity":"breaking","affected_versions":">=4.2.0"},{"fix":"Upgrade to `react-inlinesvg@4.3.0` or higher to resolve the underlying bug. Ensure your `loader` component is stable and does not cause unintended re-renders.","message":"Versions prior to 4.3.0 could experience an infinite re-render loop when using the `loader` prop, particularly if multiple SVGs loaded simultaneously.","severity":"gotcha","affected_versions":"<4.3.0"},{"fix":"If experiencing broken SVG internal references with `uniquifyIDs` and a `<base>` tag, provide the `baseURL` prop to the `SVG` component, e.g., `<SVG uniquifyIDs baseURL={window.location.href} />` or a specific path.","message":"When using `uniquifyIDs` for SVG elements (e.g., gradients, masks, clip-paths with `url()` references) and your HTML page utilizes a `<base>` tag, SVG references might break. The `baseURL` prop is essential to correctly prepend to these `url()` references and ensure they resolve properly.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade to `react-inlinesvg@4.1.8` or newer to get the fix for SSR compatibility. Ensure your SSR setup correctly handles client-side hydration.","message":"Earlier versions, particularly prior to v4.1.8, had issues with Server-Side Rendering (SSR) due to incorrect `canUseDOM` checks, leading to a mismatch between server and client rendered output or SVGs not loading on the server.","severity":"gotcha","affected_versions":"<4.1.8"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `react-inlinesvg` is up to date and compatible with your React version (check peer dependencies). You might need to add a `resolutions` field in your `package.json` for `@types/react` to enforce a specific version that aligns with your project.","cause":"This TypeScript error typically indicates a version mismatch between `react-inlinesvg`'s types and your installed React/TypeScript versions, or incorrect import of the SVG component.","error":"'SVG' cannot be used as a JSX component. Its instance type 'InlineSVG' is not a valid JSX element. The types returned by 'render()' are incompatible between these types."},{"fix":"Ensure the server hosting the SVG file has appropriate CORS headers (`Access-Control-Allow-Origin`) configured to allow requests from your domain. Verify the URL is correct and accessible.","cause":"Attempting to load a remote SVG from a different origin without proper CORS (Cross-Origin Resource Sharing) headers configured on the SVG's server, or a general network issue.","error":"Error: Failed to fetch SVG: ... Network request failed / CORS policy blocked."},{"fix":"Upgrade to `react-inlinesvg@4.3.0` or newer. If the issue persists, review how state is managed in your `loader` component or within `onError`/`onLoad` callbacks to prevent unintended re-renders.","cause":"Often related to infinite re-render loops caused by state updates within render or effects without proper dependency arrays, historically tied to the `loader` prop in older `react-inlinesvg` versions.","error":"Warning: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate."},{"fix":"Provide the `baseURL` prop to the `SVG` component. The `baseURL` should be the base URL for resolving relative `url()` references within the SVG, often `window.location.href` or a specific asset path.","cause":"Internal SVG references (like `url(#id)`) are not correctly resolving after `uniquifyIDs` processes the SVG, especially if a `<base>` tag is present in your HTML.","error":"SVG content not displayed or styles incorrect when using `uniquifyIDs`."}],"ecosystem":"npm"}